我知道,为了将设定的比值数计算在内,以下法典可以做到:
int t; // in which we want count how many bits are set
// for instance, in 3 (011), there are 2 bits set
int count=0;
while (t > 0) {
t &= (t - 1);
count++;
}
现举一个例子:
int x[] = {3, 5, 6, 8, 9, 7};
我有以下法典:
int sum = 0;
int count;
for (int i = 0; i < x.length; i++) {
count = 0;
while (x[i] > 0){
x[i] &= (x[i] - 1);
count++;
}
sum += count;
}
然而,这并不奏效。 什么是错的?