题目
方法(循环得位):
代码实现:
n与0000 0000 0000 0000 0000 0000 0000 0001相与可以知道n的最低位是不是1,0000 0000 0000 0000 0000 0000 0000 0010可以知道n的倒数第二位是不是1。以此类推,通过循环可以知道n所有位是1的个数。
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0,cur = 1,num = 31;
while(num>=0){
if((n&cur) != 0){
count++;
}
cur = cur << 1;
num--;
}
return count;
}
}
结果:
第二种代码跟第一种代码思想差不多,只是改成了n逐次右移1位。
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0,cur = 1,num = 31;
while(num>=0){
if((n&1) != 0){
count++;
}
n = n>>1;
num--;
}
return count;
}
}
结果: