Swap Even and Odd Bits
Problem statement
Given an unsigned 32-bit integer n, swap every bit at an even position with the adjacent bit at the next odd position.
Bit positions are counted from the least significant bit, starting at position 0. Therefore, swap the pairs (0, 1), (2, 3), and so on through (30, 31).
Return the resulting unsigned 32-bit integer.
Function
swapEvenOddBits(n: long) → longExamples
Example 1
n = 10return = 5The low four bits of 10 are 1010. Swapping positions (0, 1) and (2, 3) produces 0101, which equals 5.
Example 2
n = 23return = 43The low six bits of 23 are 010111. Swapping each adjacent pair produces 101011, which equals 43.
Example 3
n = 1return = 2The set bit at position 0 moves to position 1, so the result is 2.
Constraints
0 <= n <= 2^32 - 1.