1. add both variables ans assign it to first variable. x=x+y;
2.subtract the second value from that total and assign it to second. y=x-y;
3. subtract the second value from the total again and assisgn to first . x=x-y;
if x=10 and y=20 then
x=x+y----------> x= 10+20--->x=30
y=x-y----------> y=30-20 ---> y=10
x=x-y-----------> x=30-10 ----> x=20
Disagree. That solution is more of a party trick. The solution with exclusive or is definitely a party trick only.
khadar valli wrote:. . . Problem solved. . . .
Welcome to the Ranch I added code tags to your post; you should always use the tags. Doesn't it look better. What follows is a good object‑oriented solution:-…but I won't show you the workings of the IntSwapper class. You will have to write your own. If you search you will find there is a standard idiom for swapping two values like that, the same code can be used in Java®, C, C++ and C#.
Two cups are filled up with some content and one cup is empty:
Red with milk
Green with water
Blue is empty
What would you do in order to have milk in Green cup and water in Red?
I am surprised; I found it in a few seconds by searching the web.
Maneesh Weerasooriya wrote:no
Campbell Ritchie wrote:The solution with exclusive or is definitely a party trick only.
Not sure I agree completely. For one thing it's pretty much optimally fast, and for a method like List.set() that needs to return a "previous" value, it's actually quite elegant IMO:But I certainly wouldn't make a habit of it.
Campbell Ritchie. That solution is more of a party trick. The solution with exclusive or is definitely a party trick only.[/quote wrote:
But your solution violates the instructions that no new ints be created. Presumably this assignment was meant specifically to discover how XOR of something similar can be used. Your point, however, is well taken - one should never use clever tricks that can make the code difficult to maintain.