Posts Swap all odd and even bits (geeksforgeeks - SDE Sheet)
Post
Cancel

Swap all odd and even bits (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given an unsigned integer N. The task is to swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43(00101011). Here, every even position bit is swapped with an adjacent bit on the right side(even position bits are highlighted in the binary representation of 23), and every odd position bit is swapped with an adjacent on the left side.

geeksforgeeks

SOLUTION

We start by creating two variables: one to capture the bits at even positions and another to capture the bits at odd positions. To do this, we perform an AND operation between the number N and these two variables. This isolates the even and odd bits separately.

Next, we shift the even-positioned bits to the right and the odd-positioned bits to the left, effectively swapping them. Finally, we combine these shifted bits to get the result where all odd and even bits have been swapped.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution
{

    public static int swapBits(int n)
    {

        // init:
        // evenBit: num which has a set bit for all even positions
        // oddBit: num which has a set bit for all odd positions
        int evenBit = 0b10101010101010101010101010101010; // == Integer.parseInt("10101010101010101010101010101010", 2);
        int oddBit  = 0b01010101010101010101010101010101;

        // retain only the even positions
        evenBit = (evenBit & n);

        // retain only the odd positions
        oddBit = (oddBit & n);

        // after swapping, the even bit will be right shifted by 1 position
        int evenBitShifted = evenBit >> 1;

        // after swapping, the odd bit will be left shifted by 1 position
        int oddBitShifted = oddBit << 1;

        // the result will be a combination of the left and right shifted values
        return evenBitShifted | oddBitShifted;

    }

}
This post is licensed under CC BY 4.0 by the author.