Given an integer, swap adjacent bits of it. In other words, swap bits present at even positions with those present in odd positions.

For example,

Input:  761622921 (00101101011001010111000110001001)
 
Output: 513454662 (00011110100110101011001001000110)
 
Explanation: (Every pair of adjacent bits swapped)
 
00 10 11 01 01 10 01 01 01 11 00 01 10 00 10 01
00 01 11 10 10 01 10 10 10 11 00 10 01 00 01 10

Practice this problem

The idea is to separate bits present at even positions with bits present at odd positions using mask 0xAAAAAAAA and 0x55555555, respectively.

  • Mask 0xAAAAAAAA has all its even bits set, and its bitwise AND with n will separate bits present at even positions in n.
  • Similarly, mask 0x55555555 has all its odd bits set, and its bitwise AND with n will separate bits present at odd positions in n.
(0xAAAAAAAA)16 = (1010 1010 1010 1010 1010 1010 1010 1010)2
(0x55555555)16 = (0101 0101 0101 0101 0101 0101 0101 0101)2

After separating even and odd bits, right shift the even bits by 1 position and left shift the odd bits by 1 position. Now that all even bits are at odd positions and all odd bits are at even positions merge them by taking their OR. For example,

1. SEPARATE:
 
00101101011001010111000110001001   &    (n)
10101010101010101010101010101010        (0xAAAAAAAA)
————————————————————————————————
00101000001000000010000010001000        (Contains all even bits)
 
 
00101101011001010111000110001001   &    (n)
01010101010101010101010101010101        (0x55555555)
————————————————————————————————
00000101010001010101000100000001        (Contains all odd bits)
 
 
2. SHIFT & MERGE:
 
00010100000100000001000001000100   |    (Right shift even bits by 1)
00001010100010101010001000000010        (Left shift odd bits by 1)
————————————————————————————————
00011110100110101011001001000110        (Adjacent bits swapped)

Following is the C++, Java, and Python implementation based on the above idea:

C++


Download  Run Code

Output:

761622921 in binary is 00101101011001010111000110001001
 
After Swapping…
513454662 in binary is 00011110100110101011001001000110

Java


Download  Run Code

Output:

761622921 in binary is 00101101011001010111000110001001
 
After Swapping…
513454662 in binary is 00011110100110101011001001000110

Python


Download  Run Code

Output:

761622921 in binary is 00101101011001010111000110001001
 
After Swapping……
513454662 in binary is 00011110100110101011001001000110