ntree.ai
ntree.aiNumber of 1 Bits

Solutions

1. Brute Force

O(logn) time | O(1) space

Intuition

We can find the bits of a number the same way we convert it to binary by hand. The remainder of dividing it by 2 is its last bit, and dividing it by 2 drops that bit.

So we can repeat the division until the number becomes zero and sum the remainders.

Algorithm

  1. Create a count variable with initial value 0.
  2. While n is greater than 0:
    • Add the remainder of n divided by 2 to count.
    • Divide n by 2, dropping the remainder.
  3. Return count.
11
1
0
1
1
11 % 2 = 1, count = 1, 11 / 2 = 5
1 / 5

Code

Code
Python
def hammingWeight(n: int) -> int:
    count = 0
    while n:
        count += n % 2
        n //= 2
    return count
/**
 * @param {number} n
 * @returns {number}
 */
var hammingWeight = function (n) {
  let count = 0
  while (n !== 0) {
    count += n % 2
    n = Math.floor(n / 2)
  }
  return count
}
class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            count += n % 2;
            n /= 2;
        }
        return count;
    }
}

2. Clear the Last 1 Bit

O(k) time | O(1) space, for k 1 bits

Intuition

n & (n - 1) operation removes the last 1 bit of n. This happens because n - 1 turns the last 1 bit into 0 and every 0 bit after it into 1.

So we can repeat this operation until n is zero where the number of iterations is the number of 1 bits.

Algorithm

  1. Create a count variable with initial value 0.
  2. While n is greater than 0, replace n with n & (n - 1) and increase count by one.
  3. Return count.
1
0
1
1
11
&
1
0
1
0
10
1
0
1
0
10
11 & 10 = 10, count = 1
1 / 4

Code

Code
Python
def hammingWeight(n: int) -> int:
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count
/**
 * @param {number} n
 * @returns {number}
 */
var hammingWeight = function (n) {
  let count = 0
  while (n !== 0) {
    n &= n - 1
    count++
  }
  return count
}
class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n &= n - 1;
            count++;
        }
        return count;
    }
}
def hammingWeight(n: int) -> int:
pass
 

Press Visualise to step through your code.