How to Swap Two Numbers Without Using Third Variable | Number Swapping | C Programming Tutorial

preview_player
Показать описание
How to Swap Two Numbers Without Temp or Third Variable in Java - Interview Question Example

How to swap two numbers without using temp or third variable is a common interview question not just on Java interviews but also on C and C++ interviews. It is also a good programming question for freshers. This question was asked to me long back and didn't have any idea about how to approach this question without using temp or third variable, maybe lack of knowledge on bitwise operators in Java or maybe it didn't click at that time. Given some time and trial error, I eventually come out with a solution with just an arithmetic operator but the interviewer kept asking about other approaches of swapping two variables without using temp or third variable.

Personally, I liked this question and included in the list of my programming interview question because of its simplicity and some logical work, it forces you to do. 

When I learned bit-wise operation in Java I eventually find another way of swapping two variables without a third variable, which I am going to share with you guys.

you have ever heard this question, then you must be familiar with this approach of swapping numbers without using the temp variable. If you are hearing it the first time, then try it yourself, it's a good programming exercise for an absolute first-timer. By the way, here is the code example of swapping two numbers without using temp variable and using the arithmetic operator 

Bitwise operators can also be used to swap two numbers without using a third variable. XOR bitwise operator returns zero if both operands are the same i.e. either  0 or 1 and return 1 if both operands are different e.g. one operand is zero and the other is one. 

By leveraging this property, we can swap two numbers in Java. Here is a code example of swapping two numbers without using temp variable in Java using XOR bitwise operand:

There is another, third way of swapping two numbers without using a third variable, which involves multiplication and division operator. This is similar to the first approach, where we have used + and - operators for swapping values of two numbers. 

Here is the code example to swap two numbers without using a third variable with division and multiplication operators

That's all on 3 ways to swap two variables without using a third variable in Java. Its good to know multiple ways of swapping two variables without using temp or third variable to handle any follow-up question. Swapping numbers using a bitwise operator is the fastest among the three because it involves a bitwise operation. 

It’s also a great way to show your knowledge of bitwise operators in Java and impress the interviewer, which then may ask some questions on a bitwise operation. A nice trick to drive interviews in your expert area.
Рекомендации по теме