举个栗子: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;
}
}
京公网安备 11010502036488号