Bird
Raised Fist0

Identify the bug in the following code snippet for bitwise AND of numbers range:

medium🐞 Bug Identification Q14 of Q15
Bit Manipulation - Bitwise AND of Numbers Range
Identify the bug in the following code snippet for bitwise AND of numbers range:
AThe bit-clearing operation 'right = right & (right - 1)' is incorrect.
BThere is no bug; the code works correctly.
CThe function should return 'left' instead of 'right'.
DThe loop condition should be 'right > left' instead of 'right != left'.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop condition

    The loop runs while right != left, which fails if right < left, causing infinite loop or incorrect behavior.
  2. Step 2: Correct condition

    Changing condition to 'right > left' ensures loop terminates when right reaches or goes below left.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Loop condition must prevent infinite loops and handle equality correctly [OK]
Quick Trick: Loop condition must be 'right > left' to terminate properly [OK]
Common Mistakes:
MISTAKES
  • Using '!=' instead of '>' causes infinite loops
  • Misunderstanding bit-clearing operation
  • Returning wrong variable
Trap Explanation:
PITFALL
  • '!=' looks correct but fails when right < left, a subtle boundary bug.
Interviewer Note:
CONTEXT
  • Tests attention to loop boundary conditions and subtle off-by-one errors.
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