Ecommet

Number of 1 Bits

Easy Problem 146 of 151 Java and Python

Problem

Given a positive integer n, return the number of 1 bits in its binary representation (its Hamming weight).

Example 1

Input
n = 11
Output
3
Why
11 is 1011 in binary.

Example 2

Input
n = 128
Output
1
Why
10000000.

Constraints

  • 1 ≤ n ≤ 2³¹ – 1

Explanation

Checking all 32 bits works. A neater trick: n & (n - 1) clears the lowest set bit of n. Repeat until n is 0 and count the steps; the loop runs once per set bit.

Approach 1 · Naive

Check every bit

  • Time O(32)
  • Space O(1)

Look at the lowest bit, add it to the count, and shift right, 32 times.

  1. While n != 0: add n & 1, then shift n right by one.
Java
class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            count += n & 1;
            n >>>= 1;
        }
        return count;
    }
}
Python
class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0
        while n:
            count += n & 1
            n >>= 1
        return count

Approach 2 · Optimal

Clear the lowest set bit

  • Time O(number of set bits)
  • Space O(1)

Each n &= n - 1 removes exactly one set bit.

  1. While n != 0: n &= n - 1, count++.
Java
class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n &= n - 1;
            count++;
        }
        return count;
    }
}
Python
class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0
        while n:
            n &= n - 1
            count += 1
        return count

Complexity compared

ApproachTimeSpace
Naive Check every bitO(32)O(1)
Optimal Clear the lowest set bitO(number of set bits)O(1)

Key takeaways

  • n & (n - 1) == 0 also tests whether n is a power of two.
  • In Java use >>> (unsigned shift) when bits may be negative; >> copies the sign bit forever.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem