Number of 1 Bits

EasyBit Manipulation🧩 Bit ManipulationLeetCode #191 ↗Updated

Problem

Count how many bits are set to 1 in the 32-bit binary form of the integer n (its Hamming weight). Treat n as an unsigned pattern of bits, so a negative Java int such as -1 counts all 32 of its bits.
Inputn = 11 (binary 1011)Output3
Inputn = 128 (binary 10000000)Output1
Inputn = 2147483645Output30

n fits in 32 bits  ·  Follow-up: the function is called many times — how would you speed it up?

Try it yourself

Java
class Solution {
    public int hammingWeight(int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
n & (n − 1) erases exactly the lowest set bit, so you can loop once per set bit. For heavy repeated use, precompute counts for every byte and answer with four table lookups.
PatternBit Manipulation

Instinct Pairs that cancel, counting 1s, powers of two, subsets as numbers, or 'no + or - allowed' - drop to binary and use XOR, AND, OR and shifts.

Memory hack XOR is a forgetful twin detector - see something twice and it vanishes; n & (n-1) snips off the last lit bulb.

Open the Bit Manipulation guide →

Approaches

Brute ForceCheck All 32 Positions

Time O(32)Space O(1)

Look at the lowest bit with n & 1, add it to the count, then shift with the unsigned >>> so the sign bit doesn’t get copied in. Repeat 32 times.

Java
public int hammingWeight(int n) {
    int count = 0;
    for (int i = 0; i < 32; i++) {
        count += n & 1;
        n >>>= 1; // unsigned shift: works for negative n too
    }
    return count;
}

Always 32 iterations, even for n = 1.

At a glance

LevelApproachTimeSpace
Brute ForceCheck All 32 PositionsO(32)O(1)
BetterClear Lowest Set Bit (Kernighan)O(k), k = set bitsO(1)
OptimalByte Lookup TableO(1) per callO(1) (256 entries)
Common pitfalls
  • Using >> on a negative int — sign extension makes the loop never end.
  • Looping while (n > 0) — skips negative inputs entirely.
  • Forgetting the & 0xFF mask when indexing the table.
Interview tips
  • Explain why n & (n − 1) clears the lowest set bit with a 4-bit example.
  • Call out Java’s lack of unsigned ints and the need for >>>.
  • Answer the follow-up with the lookup table (or hardware bitCount).
Pattern
Lowest-set-bit trick → count, iterate or remove set bits in O(number of ones).
My notes saved in this browser