**Question : Given a number and 2 indices return the number after swapping bits present at those indices.**

**Method-1 : Brute-Force**

We can swap bits by following the given steps :-

1. Using bitmasks to extract the i^{th} and j^{th }bits.

2. Save the extracted bits to some local variables.

3. Write the j^{th }bit to the i^{th} position and vice-versa.

int bitSwapBruteForce(int x, int i, int j){ int temp1= ((x & (1<<i)) !=0); int temp2= ((x & (1<<j)) !=0); x = temp1==1 ? (x | ( temp1<<j) ) : (x & ~(1<<j)); x = temp2==1 ? (x | ( temp2<<i) ) : (x & ~(1<<i)); return x; }

**The Time Complexity : O(1)**, only a constant amount of operations are required.

**The Space Complexity : O(1)**, only a constant amount of extra space required.

**Method-2 :** **Oh! Its beauty.**

Since a bit can take only two values we can do better, lets swap only when bits differ. We’ll use the magical XOR once again.

int bitSwapSuccinct(int num, int i, int j){ if( ( ( num>>i ) & 1 ) != ( ( num>>j ) & 1 ) ){ int bitMask = (1<<i) | (1<<j); num ^=bitMask; } return num; }

As i^{th} and j^{th} bits of num differ, only 1 of them would be 1, resulting in bitMask having only one 1 in its bit representation. Now the XOR would swap the bits with help of bitMask.

For num=(1110)_{2}, i=0, j=2;

bitMask=(1)_{2} | (100)_{2} = (101)_{2}

num = (1110)_{2} XOR (0101)_{2} = (1011)_{2}

**The Time Complexity : O(1)**, only a constant amount of operations are required.

**The Space Complexity : O(1)**, only a constant amount of extra space required.

The full working code is available at Github, you can star the repository to get updates. You can also follow this blog for more such posts. Comment in your queries, report bugs, discuss!