programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# need help with an algorithem

jopus steick
Greenhorn
Posts: 2
i need to write a method (i do it in C++ but in java its also good)
that except one argument (one int) which is 4 or 7.
if it gets a 4 it needs to return 7.
if it gets 7 it needs to return 4.
U CANT USE IF,OR SWITCH OR ANY OTHER DECISION STRUCTURE!!!
i couldnt solve it...any idea how to do it???

Carl Trusiak
Sheriff
Posts: 3341
Sounds like a class assignment. The answer can be determined by reading Cat and Mouse Games with Bits

Post your solution and I'll compare it to mine

jopus steick
Greenhorn
Posts: 2
i couldnt even understand it...since im at work.
ppplz pppplllz gimmie a solution...(-:

gonna read it at home in about 15 hours )-: for sure.

sasi kala
Ranch Hand
Posts: 68
Hi,
i got one solution....

FileName: Magic.java

output:

Hope This Helps.

All The Best

Carl Trusiak
Sheriff
Posts: 3341
That works or something like:

Which is probably what the instructor is looking for.

Why this works
7 in binary is 000000111
4 in binary is 000000100
3 in binary is 000000011
The ^ (XOR) operation will set a bit in the result if the bit is set in one of the operands but, not in the other.
So 7 ^ 3, the third bit is set in 7 but not 3 so it set in the result. The second and first are set in both 7 and 3 so it's not set in the result. The result becomes 4
I think you can rationalize 4 ^3

sasi kala
Ranch Hand
Posts: 68
good one

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?