DEV Community

Rahul Parshi
Rahul Parshi

Posted on

Swapping 2 variables(numbers, characters, strings, booleans) without using extra variable

Numbers

Using arithmetic operation

 a = a + b; b = a - b; // (a+b) - (b) = a a = a - b; // (a+b) - (a) = b 
Enter fullscreen mode Exit fullscreen mode

Using binary operation

 a = a ^ b; b = a ^ b; // (a ^ b) ^ (b) = a ^ 0 = a a = a ^ b; // (a ^ b) ^ (a) = 0 ^ b = b 
Enter fullscreen mode Exit fullscreen mode

Characters

If characters are stored with it's ASCII value like C++, same method as numbers can be used. Else characters can be type caste to numbers.

 a = (char) ((int)a ^ (int)b); b = (char) ((int)a ^ (int)b); a = (char) ((int)a ^ (int)b); 
Enter fullscreen mode Exit fullscreen mode

Strings

 a = a + b; b = a.substr(0, (a.length() - b.length())); a = a.substr(b.length(), a.length()); 
Enter fullscreen mode Exit fullscreen mode

Space complexity = S(M + N) where M is length of a and N is length of b;

Booleans

If both the variables are same, swapping is not required else need to toggle the values.

 if (a != b){ a = true ^ a; //toggles the value b = true ^ b; } 
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
parshirahul profile image
Rahul Parshi

In javascript, to swap 2 variables.

[a, b] = [b, a]; 
Enter fullscreen mode Exit fullscreen mode