150NeetCode 150

145.Number of 1 Bits

EasyBlind 75Bit Manipulation ยท 2/7

Problem

Given a positive integer n, return the number of set bits (bits equal to 1) in its binary representation. This count is also known as the Hamming weight.

Examples

Input:  n = 11
Output: 3
Explanation: 11 in binary is 1011, which has three 1 bits.
Input:  n = 128
Output: 1
Explanation: 128 in binary is 10000000, a single 1 bit.
Input:  n = 2147483645
Output: 30
Explanation: 2147483645 = 1111111111111111111111111111101 (31 bits), thirty of which are 1.

Constraints

  • 1 <= n <= 2^31 - 1

๐Ÿ’ก Key Insight

n & (n - 1) clears the lowest set bit of n: subtracting 1 turns the lowest 1 into 0 and all zeros below it into 1s, and the AND wipes out that whole tail. So repeating n &= n - 1 until n == 0 takes exactly as many iterations as there are 1 bits โ€” no need to visit the zeros at all.

Brute Force (Check All 32 Bits)

TimeO(32) = O(1)SpaceO(1).

Intuition

An int has 32 bit positions. For each position i, shift n right by i and check whether the lowest bit is 1.

Algorithm

  1. count = 0.
  2. For i from 0 to 31: if ((n >> i) & 1) == 1, increment count.
  3. Return count.

Visualization

n = 11 = ...0000 1011
i=0: 1 โœ“   i=1: 1 โœ“   i=2: 0     i=3: 1 โœ“   i=4..31: 0
count = 3

Code

java
class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        for (int i = 0; i < 32; i++) {
            if (((n >> i) & 1) == 1) { // is bit i set?
                count++;
            }
        }
        return count;
    }
}

Complexity

  • Time: O(32) = O(1) โ€” always 32 iterations.
  • Space: O(1).

Complexity Comparison

Approach Time Space
Check All 32 Bits O(32) O(1)
Shift Until Zero O(highest bit position) O(1)
Brian Kernighan O(number of set bits) O(1)

Common Pitfalls

  • Using the signed shift >> in a while (n != 0) loop โ€” for a negative n the sign bit is copied in forever and the loop never ends. Use >>>.
  • Writing n & 1 == 1 without parentheses โ€” in Java == binds tighter than &, so it does not compile (or means something else in other languages). Write (n & 1) == 1.
  • Using n % 2 and n / 2 โ€” they behave differently for negative numbers (-3 % 2 == -1), which matters in the variant where the input is treated as an unsigned 32-bit value.
  • Forgetting that n - 1 borrows through trailing zeros โ€” that borrow is exactly why the Kernighan trick removes only the lowest set bit.