Paths Subjects Questions Quizzes Pricing Search
Advanced Open Pro

Swap Odd and Even Bits

Given a 32-bit unsigned integer n, swap every pair of adjacent bits: bit 0 swaps with bit 1, bit 2 swaps with bit 3, bit 4 swaps with bit 5, and so on up through bit 30 swapping with bit 31 (bits are indexed from 0 at the least-significant end). Return the resulting 32-bit integer.

You must solve this using bitmasks and shifts — do not convert the number to a string/list of characters and manipulate it that way.

Example 1

Input: n = 0b00000010 (decimal 2)
Output: 0b00000001 (decimal 1)
Explanation: bit 1 is set and bit 0 is clear; after swapping the
pair (bit 0, bit 1), bit 0 becomes set and bit 1 becomes clear.

Example 2

Input: n = 0b00000101 (decimal 5)
Output: 0b00001010 (decimal 10)
Explanation: bits 0 and 2 are set (the "even" positions). After
swapping each pair, bits 1 and 3 end up set (the "odd" positions
of the corresponding pairs).

Constraints

  • 0 <= n <= 2^32 - 1
  • Treat n as a fixed-width 32-bit unsigned integer.

Share this question

← Back to Bit Manipulation practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.