One of the very tricky questions asked in an interview.
Swap the values of two variables like a=10
and b=15
.
Generally to swap two variables values, we need 3rd variable like:
temp=a;
a=b;
b=temp;
Now the requirement is, swap values of two variables without using 3rd variable.
Here is one more solution but a single risk.
code:
any value at location a+1 will be overridden.
If you change a little the question to ask about 2 assembly registers instead of variables, you can use also the
xchg
operation as one option, and the stack operation as another one.You may do....in easy way...within one line Logic
or
As already noted by manu, XOR algorithm is a popular one which works for all integer values (that includes pointers then, with some luck and casting). For the sake of completeness I would like to mention another less powerful algorithm with addition/subtraction:
Here you have to be careful of overflows/underflows, but otherwise it works just as fine. You might even try this on floats/doubles in the case XOR isn't allowed on those.
Swapping two numbers using third variable be like this,
Swapping two numbers without using third variable
Of course, the C++ answer should be
std::swap
.However, there is also no third variable in the following implementation of
swap
:Or, as a one-liner: