Swap Odd and Even Bits
Treat n as a **32-bit unsigned integer**. Number its bit positions from 0 (least significant) to 31 (most significant): positions 0, 2, 4, …, 30 are the "even" positions, and 1, 3, 5, …, 31 are the "odd" positions.
Swap every adjacent pair of bits — the bit at even position 2k trades places with the bit at odd position 2k + 1, for each k from 0 to 15 — and return the resulting integer.
For example, for n = 23 (binary ...00010111), pairing bits from the low end gives (bit0, bit1) = (1, 1), (bit2, bit3) = (1, 0), (bit4, bit5) = (1, 0). Swapping each pair yields bits 1, 1, 0, 1, 0, 1 (positions 0 through 5), which is 43.
Example cases
- single odd bit setin n = 2out 1n = 2 has only bit 1 (odd) set; swapping moves it to bit 0, giving 1.
- mixed bitsin n = 23out 4323 = binary ...10111. Swapping each adjacent pair gives ...101011 = 43.
- zeroin n = 0out 0No bits are set, so there's nothing to swap.
- all 32 bits setin n = 4294967295out 4294967295Every pair is (1, 1); swapping a pair of identical bits is a no-op.
Constraints
- 0 <= n <= 2^32 - 1
n =
2