MadanRevoor.com | Aesthetic Web design using Wordpress and JQuery | { This site sponsored by Gatwick Airport Parking }
This was one of those weird questions that got popped at me during a recent recruitment process. I tried to attempt it using XOR logic which I had read at a c programming tutorial page. The XOR truth table is unique in the sense that when both inputs are opposite (i.e a=true/ON and b=false/OFF), then the output is true or ON. Otherwise, the output is false or OFF.
The truth table for XOR (Exclusive OR) is shown below:
| A | B | O/P |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 0 |
The solution is as follows.
Assume int a = 5; and int b = 3;
Now to swap them using XOR, one has to do the following
a = a xor b; // 5 ^ 3 = 6
b = a xor b; // 6 ^ 3 = 5
a = a xor b; //6 ^ 5 = 3
That’s it! we have swapped the two variables without using a temp variable. We saved resources when we could have easily wasted a few more bytes! Now, there’s an other way to do it. Why would you need a XOR when you could do it with the common ‘+’? Well, I needed some assistance to figure out it was the same logic to do a swap with the common and more preferred additive ‘+’ operator. Here is the solution.
a = a + b; //a = 8 (sum of the two variables)
b = a - b; // b = 8 - 3 = 5
a = a - b; //a = 8 - 5 = 3
Phew! At the end of it, I could not but wonder what weird questions get popped at you during an interview. Hope you enjoy your next one!
This entry was posted on Tuesday, February 10th, 2009 at 1:59 am and is filed under C Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.