## DEV Community is a community of 661,237 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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

## 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;
}
``````