Bird
Raised Fist0

Suppose the input integer can be negative and you want to count the number of 1 bits in its 32-bit two's complement representation. Which modification ensures correct counting for all integers?

hard🎤 Interviewer Follow-up Q15 of Q15
Bit Manipulation - Number of 1 Bits (Hamming Weight)
Suppose the input integer can be negative and you want to count the number of 1 bits in its 32-bit two's complement representation. Which modification ensures correct counting for all integers?
AUse logical AND with 1 and left shift the number until it becomes zero.
BUse the naive loop with 'while n != 0' and right shift operator as is.
CConvert the integer to its absolute value before counting bits.
DMask the input with 0xFFFFFFFF before counting bits to treat it as unsigned.
Step-by-Step Solution
  1. Step 1: Understand two's complement representation

    Negative numbers have sign-extended bits; masking with 0xFFFFFFFF treats them as unsigned 32-bit values.
  2. Step 2: Apply mask before counting bits

    Masking ensures right shifts do not propagate sign bit and loop terminates correctly.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Masking with 0xFFFFFFFF handles negative inputs correctly [OK]
Quick Trick: Mask negative inputs to treat as unsigned [OK]
Common Mistakes:
MISTAKES
  • Using naive loop with signed shifts
  • Taking absolute value loses bit pattern
  • Left shift does not help counting bits
Trap Explanation:
PITFALL
  • Taking absolute value seems intuitive but changes bit pattern; naive loop fails on negatives.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to handle signed integers and bitwise operations correctly.
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