二进制中1的个数
二进制中1的个数
http://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8
举个栗子:1100 将它减1后为1011,再拿来跟原数按位与,为 1000,后面的1消除了。有多少个1就做多少次消除,每次消除用count记录下来。
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while(n != 0){
count++;
n = n &(n-1);
}
return count++;
}
}或者每次&1,计算出多少位。
public class Solution {
public int NumberOf1(int n) {
int res = 0;
while(n != 0){
res += (n & 1);
n >>>= 1;
}
return res;
}
}剑指Offer题解 文章被收录于专栏
为了之后反复练习方便查阅。

