Swap variables interview question

Swapping two variables without a temp

Given two integer variables A and B. Write C++ code to swap them without using a temporary variable.

Solution

This is a well known problem for which you can find so many references on the Internet. One way to do that is to use addition and subtraction as follows:

This is more than enough to do the job. We are using one of the variables for temporary storage instead of a separate temporary variable. Let us try to trace the code and see how it does the job:

There is a drawback of this solution however. If B + A overflows B then it is not going to work.

Solution

Another solution that does not suffer from the overflow problem is using XOR bitwise operations as
follows:

Similarly let us try to see how the the chain of XOR operations does the job.

Although it looks confusing a little bit we did nothing but substitution.

Swapping variables in c++

Here is an example C++ code that implements swap two variables algorithm:

If you have questions or comments, please use the comments section below. Thanks for visiting.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *