Bit Manipulation - Bitwise AND of Numbers RangeIdentify 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'.Check Answer
Step-by-Step SolutionSolution:Step 1: Analyze loop conditionThe loop runs while right != left, which fails if right < left, causing infinite loop or incorrect behavior.Step 2: Correct conditionChanging condition to 'right > left' ensures loop terminates when right reaches or goes below left.Final Answer:Option D -> Option DQuick 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:MISTAKESUsing '!=' instead of '>' causes infinite loopsMisunderstanding bit-clearing operationReturning wrong variableTrap Explanation:PITFALL'!=' looks correct but fails when right < left, a subtle boundary bug.Interviewer Note:CONTEXTTests attention to loop boundary conditions and subtle off-by-one errors.
Master "Bitwise AND of Numbers Range" in Bit Manipulation3 interactive learning modes - each teaches the same concept differentlyTry ItSolutionTrace
More Bit Manipulation Quizzes Find Two Missing Numbers - Find Two Missing Numbers - Quiz 1easy Find the Missing Number - Find the Missing Number - Quiz 4medium Generate All Permutations Using Bitmask DP - Generate All Permutations Using Bitmask DP - Quiz 14medium Generate All Permutations Using Bitmask DP - Generate All Permutations Using Bitmask DP - Quiz 15hard Reverse Bits - Reverse Bits - Quiz 5medium Single Number (XOR Self-Cancellation) - Single Number (XOR Self-Cancellation) - Quiz 11easy Single Number (XOR Self-Cancellation) - Single Number (XOR Self-Cancellation) - Quiz 10hard Subsets Using Bitmask - Subsets Using Bitmask - Quiz 3easy UTF-8 Validation - UTF-8 Validation - Quiz 14medium UTF-8 Validation - UTF-8 Validation - Quiz 2easy