Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
解法一:O(1);
public class Solution{
public int hammingWeight(int n){
return Integer.bitCount(n);
}
}
解法二:O(k) k=1的个数
public class Solution{
public int hammingWeight(int n){
int num=0;
while(n!=0){
num+= n&1;
n>>>=1;//这里不能用>> 因为>>>移位以后不足的用0取代 而>>移位以后直接丢弃数据,不会补充
}
return num;
}
}
解法三:O(log2(n))
public class Solution{
public int hammingWeight(int n){
int count =0;
while(n>0) {
if(n%2 != 0)count ++;
n=n/2;
}
return count;
}
}