InterviewSolution
Saved Bookmarks
| 1. |
How will you swap two numbers without the use of a third variable? |
|
Answer» This can be achieved using ARITHMETIC operations. int x = 5, y = 15; // Code to SWAP the values of x and y x = x + y; // x now BECOMES 20 y = x - y; // y becomes 5 x = x - y; // x becomes 15Or int x = 5, y = 15; // Code to swap the values of x and y x = x * y; // x now becomes 75 y = x / y; // y becomes 5 x = x / y; // x becomes 15This can ALSO be achieved using bitwise operations. int x = 5, y = 15; // Code to swap the values of x and y x = x ^ y; // x now becomes 20 y = x ^ y; // y becomes 5 x = x ^ y; // x becomes 15 |
|