Count the Set Bits in a 32-Bit Unsigned Integer
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: A bit-manipulation task that asks how many bits are set to 1 in a 32-bit unsigned integer. It tests understanding of binary representation and bitwise operations, and correct handling of inputs above the signed 32-bit range.
Constraints
- 0 <= n <= 4294967295, that is, n <= 2^32 - 1.
- Inputs above 2^31 - 1 (2147483647) are valid and must be handled as unsigned 32-bit values; because n can exceed 2^31 - 1, Java takes it as long and C++ as long long.
- The result is between 0 and 32 inclusive.
Examples
Input: (0,)
Expected Output: 0
Explanation: Minimum valid input: no bits are set.
Input: (1,)
Expected Output: 1
Explanation: Single set bit at the lowest position, bit 0.
Hints
- The answer depends only on the 32 binary digits of n, so think about how to inspect or remove them one at a time.
- Values above 2147483647 are valid: make sure nothing in your approach treats bit 31 as a sign bit.
- Check the extremes: n = 0 has no 1 bits, and n = 4294967295 has all 32 bits set.