Bird
Raised Fist0

What is the output of the following code when the input is 0?

medium🧾 Code Trace Q4 of Q15
Bit Manipulation - Number of 1 Bits (Hamming Weight)
What is the output of the following code when the input is 0?
A1
B0
C32
DError or infinite loop
Step-by-Step Solution
Solution:
  1. Step 1: Check loop condition with n=0

    Since n is 0, the while loop condition is false immediately.
  2. Step 2: Return count

    Count remains 0, so function returns 0.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Zero input yields zero set bits [OK]
Quick Trick: Loop skips if n=0, count stays zero [OK]
Common Mistakes:
MISTAKES
  • Assuming loop runs at least once
  • Confusing zero input with all bits set
Trap Explanation:
PITFALL
  • Some candidates expect loop to run once even if n=0, leading to wrong answers.
Interviewer Note:
CONTEXT
  • Tests edge case handling and loop boundary understanding.
Master "Number of 1 Bits (Hamming Weight)" 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