LeetCode Notes: Number of 1 Bits
Question
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, the input represents the signed integer.
-3
.
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
.
Follow up: If this function is called many times, how would you optimize it?
Solution One
Analysis:
Observe the characteristics of n & 1
n: 110010101001
1: 000000000001
n & 1: 000000000001
You can see that the result depends on the number in the same position as the number 1 in n, where the last number of n is 1, so the result is 1.
If every binary digit of a number uses & 1
, you can use this feature to count the number of ones. We use 1<<i
to shift left by n places.
Code:
/**
* @param {number} n-a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
let result = 0;
for(let i = 0; i <32; i++){
/**
n: 110010101001
1<<i: 000000000001
1 Shift i bits to the left, then each loop finds 1<<i the penultimate number 1 and the penultimate number of n (do not know whether it is 0 or 1), and perform the AND operation, and the result is either 0, or not 0, when it is not 0, it means 1
*/
if((n & (1 << i)) !== 0){
result ++;
}
}
return result;
};
Solution Two
Analysis:
Observe n = 6
, n.toString(2)
to obtain binary numbers
n: 110
n-1: 101
n & (n-1): 100
n & (n-1)
will convert the lowest 1 of n to 0, and do so in a loop until the result is 0, and the number of 1s can be counted
Code:
/**
* @param {number} n-a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
let result = 0;
while(n){
// n & (n-1) convert the lowest 1 of n to 0
n &= n-1;
result++;
}
return result;
};
Comments