Bird
Raised Fist0

Consider the following Python function intended to count the number of set bits in a signed 32-bit integer:

medium🐞 Bug Identification Q7 of Q15
Bit Manipulation - Number of 1 Bits (Hamming Weight)
Consider the following Python function intended to count the number of set bits in a signed 32-bit integer:
def countSetBits(n: int) -> int:
    count = 0
    while n != 0:
        count += n & 1
        n >>= 1
    return count

What is the main issue with this implementation when n is negative?
AThe loop condition should be while n > 0 instead of n != 0
BThe bitwise AND operation is invalid for negative numbers
CThe function does not initialize count correctly
DRight shift on negative numbers performs arithmetic shift, causing an infinite loop
Step-by-Step Solution
Solution:
  1. Step 1: Understand right shift on negative integers

    In Python, right shifting a negative integer performs an arithmetic shift, preserving the sign bit.
  2. Step 2: Effect on loop condition

    Because the sign bit remains 1, n never becomes zero, causing an infinite loop.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Negative n right shift keeps sign bit set, loop never ends [OK]
Quick Trick: Right shift on negative int is arithmetic, beware infinite loops [OK]
Common Mistakes:
MISTAKES
  • Assuming right shift is logical for negative numbers
  • Ignoring infinite loop possibility
  • Thinking bitwise AND fails on negatives
Trap Explanation:
PITFALL
  • Option D looks plausible but changing loop condition doesn't fix infinite loop caused by arithmetic shift.
Interviewer Note:
CONTEXT
  • Tests knowledge of bitwise operations and signed integer behavior in Python.
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