• Post Reply Bookmark Topic Watch Topic
  • New Topic

need help with an algorithem  RSS feed

 
jopus steick
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
i got one solution....

FileName: Magic.java



output:
Send 4 and Receive 7
Send 7 and Receive 4.


Hope This Helps.

All The Best
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good one
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!