Ferozeh dot Com
Expert advice on tech interviews !
about ferozeh

Ferozeh

Similar Questions


powers of 2 with bit shifting


count 1s in a byte


conver number to binary


rectangles overlap problem


fibonacci series


unit digit problem


loop optimization problem


digit of tenth place problem


detect disc rotation direction

Question

Difficulty Level: 1

  • How can you swap two integer/character variables without using a temporary variable?

Solution

Explanation Quality:2.6

This is a very basic problem, you can possibly get asked at a internship or entry level position.

The code is very basic to achieve swapping, here it goes:

 int a = 5;
 int b = 9; //we will be swapping a and b
 a = a + b; //this makes a = 14 and b is still = 9
 b = a - b; //this makes b = 5 and a = 14
 a = a - b; //this makes a = 9 and b = 5

The question is very simple but can be difficult if you don't think about adding the two variables togather. You can swap characters this way too since characters are essentially numbers.




Previous Next