Bird
Raised Fist0

Identify the bug in the following code that attempts to count the number of 1 bits in a signed 32-bit integer:

medium🐞 Bug Identification Q14 of Q15
Bit Manipulation - Number of 1 Bits (Hamming Weight)
Identify the bug in the following code that attempts to count the number of 1 bits in a signed 32-bit integer:
def hammingWeight(n: int) -> int:
    count = 0
    while n != 0:
        count += n & 1
        n >>= 1
    return count
AThe loop condition 'while n != 0' causes infinite loop for negative numbers due to sign extension.
BThe bitwise AND operation 'n & 1' is incorrect; it should be logical AND 'n && 1'.
CThe right shift operator 'n >>= 1' should be replaced with left shift to count bits correctly.
DThe initial count variable should be initialized to 1 instead of 0.
Step-by-Step Solution
  1. Step 1: Understand signed right shift behavior

    In Python, right shifting a negative number propagates the sign bit, so n never becomes zero.
  2. Step 2: Analyze loop condition

    Because n != 0 remains true for negative numbers, the loop never terminates, causing infinite loop.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Signed right shift on negative numbers causes infinite loop [OK]
Quick Trick: Signed right shift on negatives causes infinite loop [OK]
Common Mistakes:
MISTAKES
  • Confusing bitwise AND with logical AND
  • Wrong shift direction
  • Incorrect count initialization
Trap Explanation:
PITFALL
  • Logical AND looks like a syntax error but distracts; shift direction and count init are plausible but wrong.
Interviewer Note:
CONTEXT
  • Checks understanding of signed vs unsigned shifts and edge cases with negative inputs.
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