FastPrepSwap Even and Odd Bits

Swap Even and Odd Bits

Tesla logoTesla● EasyINTERNPHONE SCREEN
Learn

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) → long

Examples

Example 1

n = 10return = 5

The low four bits of 10 are 1010. Swapping positions (0, 1) and (2, 3) produces 0101, which equals 5.

Example 2

n = 23return = 43

The low six bits of 23 are 010111. Swapping each adjacent pair produces 101011, which equals 43.

Example 3

n = 1return = 2

The set bit at position 0 moves to position 1, so the result is 2.

Constraints

  • 0 <= n <= 2^32 - 1.

More Tesla problems

See Tesla hiring insights
public long swapEvenOddBits(long n) {
  // write your code here
}
n10
expected5
Checking account…