Numbers
Using arithmetic operation
a = a + b;
b = a - b; // (a+b) - (b) = a
a = a - b; // (a+b) - (a) = b
Using binary operation
a = a ^ b;
b = a ^ b; // (a ^ b) ^ (b) = a ^ 0 = a
a = a ^ b; // (a ^ b) ^ (a) = 0 ^ b = b
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);
Strings
a = a + b;
b = a.substr(0, (a.length() - b.length()));
a = a.substr(b.length(), a.length());
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;
}
Top comments (1)
In javascript, to swap 2 variables.