Number of 1 Bits

Patrick Leaton
Problem Description

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Note:

  • Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3 above, the input represents the signed integer. -3.

Follow up: If this function is called many times, how would you optimize it?

 

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

 

Constraints:

  • The input must be a binary string of length 32

 

The description was taken from https://leetcode.com/problems/number-of-1-bits/.

Problem Solution

#O(1) Time, O(1) Space
class Solution:
    def hammingWeight(self, n: int) -> int:
        if n > 2**32:
            return -1
        count = 0
        while n is not 0:
            n &= n-1
            count += 1
        return count

Problem Explanation


Since we're being asked to count the number of bits, we can solve this problem by using bit manipulation. 

If we were to get a number then use the AND operation on the number and the same number subtracted by one, we would be able to flip the least significant, far-right bit to zero. 

If we continuously did that until all the bits were zero, we would just need to count how many iterations it took.


Let's first check if the input integer is greater than thirty-two bits to satisfy the constraint given in the problem description.  If the integer is greater than thirty-two bits, we will return a negative one.

        if n > 2**32:
            return -1

 

Otherwise, let's initialize our iteration counter.

        count = 0

 

While there are still bits we need to flip to zero, we will continue setting n equal to n AND n-1.

        while n is not 0:
            n &= n-1

 

Each time we flip a bit we will increment the counter.

            count += 1

 

Once we have broken from the loop, all of the bits from the input integer were flipped to zero so we can return the count of iterations it took.

        return count


 

Additional Notes

When it comes to binary questions, it is good to remember some of the logic gate tricks like XOR and AND operations.