Bird
Raised Fist0

Examine the code below. What is the logical error that causes incorrect results for some inputs?

medium🐞 Bug Q7 of Q15
Bit Manipulation - Bitwise AND of Numbers Range
Examine the code below. What is the logical error that causes incorrect results for some inputs?
def rangeBitwiseAnd(left: int, right: int) -> int:
    while left != right:
        left >>= 1
        right >>= 1
    return left << 1
AThe function should return <code>left | right</code> instead of shifting
BThe loop condition should be <code>left < right</code> instead of <code>left != right</code>
CThe final left shift is by 1 instead of the number of shifts performed
DThe function does not handle negative numbers
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop

    The loop right shifts left and right until they are equal, but does not count how many shifts occurred.
  2. Step 2: Check return statement

    The return shifts left left by 1, regardless of how many shifts happened.
  3. Step 3: Identify bug

    Correct approach requires shifting back by the total number of shifts, not just 1.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Missing shift count causes wrong results [OK]
Quick Trick: Count shifts, then shift back by that count [OK]
Common Mistakes:
MISTAKES
  • Forgetting to track number of shifts
  • Assuming one shift back is enough
  • Misunderstanding loop condition
Trap Explanation:
PITFALL
  • Shifting back by 1 looks plausible but ignores actual shift count.
Interviewer Note:
CONTEXT
  • Tests ability to identify subtle bugs in bitwise AND range code.
Master "Bitwise AND of Numbers Range" 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