FastPrepSwap Adjacent Bits in a 32-Bit Word

Swap Adjacent Bits in a 32-Bit Word

NVIDIA logoNVIDIA● EasyFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a nonnegative integer value representing an unsigned 32-bit word, swap bits in every adjacent pair: positions 0 and 1, positions 2 and 3, and so on through positions 30 and 31. Position 0 is the least significant bit.

Return the resulting 32-bit word as a nonnegative integer. Leading zero bits are part of the word. For example, binary 1001 becomes 0110, so 9 becomes 6.

Function

swapAdjacentBits(value: long) → long

Examples

Example 1

value = 9return = 6

Low-order binary 1001 becomes 0110, which is 6.

Example 2

value = 1return = 2

The only set bit moves from position 0 to position 1.

Example 3

value = 2147483649return = 1073741826

The highest and lowest set bits move to positions 30 and 1.

Constraints

  • 0 <= value <= 4294967295.
  • Interpret value as exactly 32 unsigned bits. The input and output use a signed 64-bit integer type so every 32-bit result remains nonnegative.

More NVIDIA problems

See NVIDIA hiring insights
public long swapAdjacentBits(long value) {
    // Write your code here.
}
value9
expected6
Checking account…