Bird
Raised Fist0

Consider the following Python function that reverses bits of a 32-bit unsigned integer using divide and conquer masks:

easy🧾 Code Trace Q12 of Q15
Bit Manipulation - Reverse Bits
Consider the following Python function that reverses bits of a 32-bit unsigned integer using divide and conquer masks:
def reverseBits(n: int) -> int:
    n = ((n >> 1) & 0x55555555) | ((n & 0x55555555) << 1)
    n = ((n >> 2) & 0x33333333) | ((n & 0x33333333) << 2)
    n = ((n >> 4) & 0x0f0f0f0f) | ((n & 0x0f0f0f0f) << 4)
    n = ((n >> 8) & 0x00ff00ff) | ((n & 0x00ff00ff) << 8)
    n = ((n >> 16) | (n << 16)) & 0xffffffff
    return n

print(reverseBits(11))  # Input is 11 (binary 00000000000000000000000000001011)
What is the output of this code?
A2952790016
B3758096384
C2147483648
D3221225472
Step-by-Step Solution
Solution:
  1. Step 1: Convert input to binary

    11 in 32-bit binary is 00000000000000000000000000001011.
  2. Step 2: Reverse bits using masks

    Reversing bits yields 11010000000000000000000000000000, which is 2952790016 in decimal.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Binary reversal matches decimal 2952790016 [OK]
Quick Trick: Reverse bits of 11 -> 2952790016 decimal [OK]
Common Mistakes:
MISTAKES
  • Confusing left and right shifts
  • Forgetting to mask final result to 32 bits
  • Miscounting bit positions
Trap Explanation:
PITFALL
  • Some candidates confuse the reversed bit pattern with the original or forget masking, leading to wrong decimal output.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute bitwise operations and verify correctness.
Master "Reverse Bits" in Bit Manipulation

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bit Manipulation Quizzes