easy +10 pts

Swap Odd and Even Bits

Swap adjacent odd and even bits in an integer using bitwise operations.

Write a function `swap_odd_even_bits(n: int) -> int` that takes a non-negative integer `n` and returns the integer obtained by swapping all pairs of adjacent bits, i.e., swapping bit 0 (least significant) with bit 1, bit 2 with bit 3, and so on. For example, the binary representation of 10 is `1010`; after swapping bits we get `0101` which is 5. The input is guaranteed to be less than 2^32 (so it fits in 32 bits). Your solution must use bitwise operations; do not convert the number to strings or lists.

Constraints

0 <= n < 2^32. Time complexity O(1).

Example

>>> swap_odd_even_bits(10)
5
>>> swap_odd_even_bits(0)
0
>>> swap_odd_even_bits(1)
2
>>> swap_odd_even_bits(2)
1
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use masks to isolate even and odd bits. For a 32-bit integer, even bits mask is 0xAAAAAAAA and odd bits mask is 0x55555555.
Shift the even bits right by 1 and the odd bits left by 1, then combine with OR.
Remember to mask to 32 bits if needed, though Python integers are unbounded.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.