Leetcode[191] Number of 1 Bits

Bryan W.
2 min readFeb 1, 2021

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?

Difficulty

  • Level: Easy
  • Acceptance: 52.7 %

Solution 1 — Using String

Time Complexity: O(n), Space Complexity: O(1)

Solution 2 — Using Bits

Time Complexity: O(n), Space Complexity: O(1)

Solution 3 — One Liner

Time Complexity: O(n), Space Complexity: O(n)

Analysis

Pretty straight-forward question with solution 1 & 3 first converting the digit to a binary string before counting the number of times 1 occurs along the string.

Solution 2 deals with the number itself and bit manipulation with a mask of 1 to test if the number is odd or even. If it is odd, increase sum by one. The bits are then shifted right. This loop continues until all the bits have shifted right and the remaining number is 0.

--

--

Bryan W.

I have a passion for coding | Salesforce Developer