I know that to count the number of set bits in a number, the following code can do it:
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++;
}
Now an array example:
int x[] = {3, 5, 6, 8, 9, 7};
I have the following code:
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;
}
This does not work, however. What is wrong?