Count the Set Bits in a 32-Bit Unsigned Integer

Quick 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.

Count the Set Bits in a 32-Bit Unsigned Integer

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

Given a non-negative integer that fits in 32 unsigned bits, return how many of its bits are 1. ### Function Signature ```python def count_set_bits(n: int) -> int: ``` ### Rules - `n` is read as an unsigned 32-bit value; return the number of 1 bits among its 32 bits. - The result is between 0 and 32 inclusive. ### Constraints - `0 <= n <= 4294967295`, that is, `n <= 2^32 - 1`. - Inputs above `2^31 - 1` (2147483647) are valid: in a language whose default integer is a signed 32-bit type, the input must be handled as unsigned. ### Examples **Example 1** ```text Input: n = 11 Output: 3 ``` 11 is `1011` in binary. **Example 2** ```text Input: n = 2147483648 Output: 1 ``` Only the highest of the 32 bits is set. **Example 3** ```text Input: n = 4294967295 Output: 32 ``` All 32 bits are set.

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.

Amazon logo
Amazon
Oct 31, 2026
mediumSoftware EngineerTechnical ScreenCoding & Algorithms
0
0

Given a non-negative integer that fits in 32 unsigned bits, return how many of its bits are 1.

Function Signature

def count_set_bits(n: int) -> int:

Rules

  • n is read as an unsigned 32-bit value; return the number of 1 bits among its 32 bits.
  • The result is between 0 and 32 inclusive.

Constraints

  • 0 <= n <= 4294967295 , that is, n <= 2^32 - 1 .
  • Inputs above 2^31 - 1 (2147483647) are valid: in a language whose default integer is a signed 32-bit type, the input must be handled as unsigned.

Examples

Example 1

Input:  n = 11
Output: 3

11 is 1011 in binary.

Example 2

Input:  n = 2147483648
Output: 1

Only the highest of the 32 bits is set.

Example 3

Input:  n = 4294967295
Output: 32

All 32 bits are set.