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;
}
}
本文介绍了三种方法来计算给定整数中1的个数,包括使用内置函数、位操作和迭代求解。每种方法的时间复杂度不同,分别为O(1)、O(k)和O(log2(n))。

429

被折叠的 条评论
为什么被折叠?



