Number of 1 Bits
1 min readMay 9, 2019
Question: Write a function that takes an unsigned integer and return the number of ‘1’ bits it has (also known as the Hamming weight).
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
You may view the full question here.
Approach 1: Umm… Really not much to explain. The Leetcode Discussion forum has a plethora of information.
//Approach 1:
//Runtime: 1ms
//Memory usage: 32.4MBpublic class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n!=0){
if((n&1)==1){
count++;
}
n = n>>>1;
}
return count;
}
}
Approach 2: A little tweak —
//Approach 2:
//Runtime: 0ms
//Memory usage: 32.6MBpublic class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n!=0){
count += n&1;
n = n>>>1;
}
return count;
}
}
Find more posts here.
Cheers & Chao!