‹ DS&A interview · Socratic
DSA · Bit Manipulation · #129

Number of 1 Bits

Module 50 · difficulty 2/5·30:00starts on first keystroke

Write a function `hammingWeight(n)` that takes a non-negative integer `n` and returns the number of set bits (`1` bits) in its binary representation — also known as the Hamming weight. The input is given as the integer's value (treat it as a 32-bit unsigned number). Return the count of `1` bits.

Examples
  • n = 11 311 in binary is 1011, which has three 1 bits.
  • n = 128 1128 in binary is 10000000, which has a single 1 bit.
  • n = 2147483645 302147483645 in binary is 1111111111111111111111111111101, which has thirty 1 bits.
Constraints
  • · 0 <= n <= 2^31 - 1
  • · n is a non-negative integer fitting in 32 bits.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.