Skip to main content

Command Palette

Search for a command to run...

Odd-Even Binary Bit Swap

Updated

Problem

Given a non-negative integer, swap the odd and even bits in its binary representation.

Example

Let's take the number 23 as an example:

1. The binary representation of 23 is 0b10111 (5 bits).

2. After padding with 0, it becomes 0b010111 (6 bits).

3. Swapping odd and even bits: 0b010111 -> 0b101011.

4. 0b101011 in decimal is 43.

Solution

1. Treat every two binary bits as one quaternary digit, simplifying the problem to a quaternary number conversion.

2. Establish a mapping relationship: 00->00, 01->10, 10->01, 11->11, corresponding to the array [0, 2, 1, 3].

3. Iterate through each quaternary digit of the input, using the mapping array for conversion.

4. Recombine the converted quaternary number into a decimal result.

Implementation

def swap_binary_bits_arithmetic(number):
    result = 0
    position = 0
    bit_swap_map = [0, 2, 1, 3]

    while number != 0:
        current_quad = number % 4
        swapped_quad = bit_swap_map[current_quad]
        result += swapped_quad * (4 ** position)
        number //= 4
        position += 1

    return result

def swap_binary_bits_bitwise(number):
    result = 0
    position = 0
    bit_swap_map = [0, 2, 1, 3]

    while number:
        current_quad = number & 3
        swapped_quad = bit_swap_map[current_quad]
        result |= swapped_quad << position
        number >>= 2
        position += 2

    return result