力扣
关于负数的自己没想出来,这是书中的两种算法,关于位运算的知识还是得要学习一个啊。。。
解1
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
int time = 32;
while (time > 0) {
count += n & 1;
n = n >> 1;
--time;
}
return count;
}
}
解2
public 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 >>>= 1; // 注意:Java中无符号右移操作
}
return count;
}
}
Solution1:
class Solution {
public:
int NumberOf1(int n) {
int count=0;
unsigned int flag=1;
while(flag){
if(n&flag)
count++;
flag=flag<<1;
}
return count;
}
};
Solution2:
class Solution {
public:
int NumberOf1(int n) {
int count=0;
while(n){
++count;
n=(n-1)&n;
}
return count;
}
};