假设十进制的数为x,让x和x-1进行&运算,每次都会消耗一位1,计数器统计到x = 0为止。
public class Solution {
public int countOfOne(int x) {
int count = 0;
while (x != 0) {
x = x & (x - 1);
++count;
}
return count;
}
}