<AI/>
enru
Все статьи

Number of 1 bits

LeetCode 191: Count the set bits (Hamming weight) of an integer with a bit mask or by clearing the lowest set bit.

Сложность
Легкая
Опубликовано
Темы
#bit manipulation
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

Write a function that takes a positive integer and returns the number of set bits (bits equal to 1) in its binary representation.

The number of set bits is also known as the Hamming weight.

Constraints

  • n is in the range from 1 to 231 - 1

Examples

Input: n = 11

Answer: 3

Explanation: The binary representation of the number has three set bits in total: 1011.

Pop Count approach

As the first solution, let's consider the most intuitive approach: literally count the ones in the binary representation of the number. This is called population count, or pop count.

However, instead of converting the number to binary in some special way and then iterating over each bit, we'll use a trick, as usual.

From the problem statement we know that n is in the range from 1 to 231 - 1. This means we're dealing with 32-bit numbers, i.e. n has at most 32 bits.

Let's take the number 13 as an example and write it in binary.

13 -> 1101

To find out whether a particular bit of a number is one, we can AND that bit with 1 and look at the result. If the result is 1, the bit is 1 too. Otherwise, the bit is zero.

This follows from the rules of bitwise AND. If one operand is always one, the result can only be one if the other operand is 1 as well.

  • 0 & 1 = 0
  • 1 & 1 = 1

This means we can go over each of the 32 bits of n and AND it with 1. If the result is one, we increment the set bit counter by 1. After checking all 32 bits, the counter holds the number of set bits.

But how do we do that? Every programming language has a bitwise AND operator for two numbers: &. It takes two numbers, ANDs them bit by bit and produces a third number whose binary representation is the result of that operation.

We create a mask mask, which is actually just an integer, and a counter count. The initial value of mask is 1. Let's walk through an example.

We write our number 13 and the mask in binary and AND them.

1101 & 0001 = 0001 = 1

The result is positive, so the first bit of n is one. We increment count by 1. Now we shift the one in the mask one position to the left and do the same.

1101 & 0010 = 0000 = 0

The result is zero, so the second bit of n is zero. In this case we don't increment the counter. Then we apply the same algorithm to the remaining bits.

1101 & 0100 = 0100 = 4

Since the result is 4 rather than 0, the bit of n at the position of the mask's one is also one. We increment count by 1.

1101 & 1000 = 1000 = 8

By the same logic, the most significant bit of n is also one. So we get count = 3, i.e. the number n = 13 has three set bits.

One last question: how do we shift the one in the mask? For that we use the left shift operator <<.

typescript
export const hammingWeightPopCount = (n: number): number => {
  let mask = 1;
  let count = 0;
 
  for (let i = 0; i < 32; i++) {
    if (n & mask) {
      count++;
    }
    mask <<= 1;
  }
 
  return count;
};

Complexity Analysis

Time Complexity

Since we know that n takes at most 32 bits, we need to perform 32 checks in the loop. Because the number of iterations is fixed, the complexity can be considered constant: O(1).

Space Complexity

O(1): the additional memory is constant.

Clearing the lowest set bit

We can make the previous algorithm simpler and a bit faster.

The key idea is that ANDing n with n - 1 always turns the lowest set bit of n into 0, while all other bits stay the same.

Let's look at an example.

Lowest set bit n = 58 1 1 1 0 1 0 n-1 = 57 1 1 1 0 0 1 n&(n-1) = 56 1 1 1 0 0 0 Flips to 0 Lowest set bit n = 52 1 1 0 1 0 0 n-1 = 51 1 1 0 0 1 1 n&(n-1) = 48 1 1 0 0 0 0 Flips to 0

Instead of checking every bit of the number, we repeatedly flip the least significant set bit to 0 and add 1 to our counter. Each time, we replace n with the result of the AND.

As soon as n becomes 0, we know there are no more ones left in it. This means count holds the correct number of ones that were in the binary representation of n.

typescript
export const hammingWeight = (n: number): number => {
  let count = 0;
 
  while (n != 0) {
    count++;
    n &= n - 1;
  }
 
  return count;
};

Complexity Analysis

Time Complexity

The running time depends on the number of set bits in n.

In the worst case all bits of n are set. Since we know that n takes at most 32 bits, we need at most 32 loop iterations. Because the number of iterations is bounded, the complexity can be considered constant: O(1).

Space Complexity

O(1): the additional memory is constant.