Brain Teasers
Variable Switch
You're a computer programmer, and the program you're writing has numeric variables A and B. You need the computer to switch the variables so that the number in variable A becomes variable B, and the number in variable B becomes variable A. Adding a third variable would use more memory though, so how can you do that switch without using another variable? Use commands such as B=B-A to assign a new value to B.
Hint
You can do it in three steps.Answer
B = A+BA = B-A
B = B-A
Using an example, if A=5 and B=4:
B = 5+4
A = 9-5
B = 9-4
A is now 4 and B is now 5.
Hide Hint Show Hint Hide Answer Show Answer
What Next?
View a Similar Brain Teaser...
If you become a registered user you can vote on this brain teaser, keep track of which ones you have seen, and even make your own.
Solve a Puzzle
Comments
i got it...i solved it by another answer
A=B-A
B=B-A
A=A+B
A=B-A
B=B-A
A=A+B
i got it...i solved it by another answer
A=B-A
B=B-A
A=A+B
A=B-A
B=B-A
A=A+B
How about this way?
A = A + B
B = A - B
A = A - B
A = A + B
B = A - B
A = A - B
This was a real exercise I got in a course.
The smart alec answer is to emply some assembler and use registers, e.g.
load location of A to register X
load location of B to register Y
save X to location of B
save Y to location of A
load location of A to register X
load location of B to register Y
save X to location of B
save Y to location of A
To post a comment, please create an account and sign in.
Follow Braingle!