Bit Manipulation - Counting Bits (0 to N)Given the following code using Brian Kernighan's bit counting trick, what is the output of countBits(5)?A[0, 1, 1, 2, 1, 2]B[0, 1, 2, 2, 1, 3]C[0, 0, 1, 1, 2, 2]D[1, 1, 1, 2, 2, 2]Check Answer
Step-by-Step SolutionSolution:Step 1: Trace countBits for i=0 to 50 -> 0 bits; 1 -> 1 bit; 2 (10) -> 1 bit; 3 (11) -> 2 bits; 4 (100) -> 1 bit; 5 (101) -> 2 bits.Step 2: Confirm output list matches countsOutput is [0,1,1,2,1,2].Final Answer:Option A -> Option AQuick Check:Matches expected counts for 0 to 5 [OK]Quick Trick: Brian Kernighan's trick counts set bits by clearing lowest set bit [OK]Common Mistakes:MISTAKESOff-by-one in loopMiscounting bits for 3 or 5Confusing count initializationTrap Explanation:PITFALLCandidates often miscount bits for numbers with multiple set bits or forget to include 0.Interviewer Note:CONTEXTTests candidate's ability to trace bit manipulation code correctly
Master "Counting Bits (0 to N)" in Bit Manipulation3 interactive learning modes - each teaches the same concept differentlyTry ItSolutionTrace
More Bit Manipulation Quizzes Bitwise AND of Numbers Range - Bitwise AND of Numbers Range - Quiz 5medium Power of Four - Power of Four - Quiz 3easy Power of Four - Power of Four - Quiz 14medium Single Number (XOR Self-Cancellation) - Single Number (XOR Self-Cancellation) - Quiz 12easy Single Number (XOR Self-Cancellation) - Single Number (XOR Self-Cancellation) - Quiz 7medium Sum of Two Integers Without + Operator - Sum of Two Integers Without + Operator - Quiz 2easy Sum of Two Integers Without + Operator - Sum of Two Integers Without + Operator - Quiz 7medium Sum of Two Integers Without + Operator - Sum of Two Integers Without + Operator - Quiz 8hard Sum of Two Integers Without + Operator - Sum of Two Integers Without + Operator - Quiz 3easy UTF-8 Validation - UTF-8 Validation - Quiz 13medium