Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-141

Swap Odd and Even Bits

Problem

Swap every pair of adjacent bits in the binary representation of a non-negative integer n and return the result.

Mask the even-position bits with 0xAAAAAAAA and shift them right, mask the odd-position bits with 0x55555555 and shift them left, then OR the two parts. Bits are numbered from 0 at the least significant position.

Hint

The two masks select alternating bits, so shifting each part by one places them in the other slot.

Test cases

case 1
in: [2]
expected: 1
case 2
in: [3]
expected: 3
case 3
in: [0]
expected: 0
case 4
in: [5]
expected: 10
case 5
in: [10]
expected: 5
Starter codePython
def swap_odd_even_bits(n):
    # Your code here
    pass

5 test cases · run your code against them in the editor