Please help to solve this problem and explain the logic. I don't know how the & operator is working here.
void main() {
int a = -1;
static int count;
while (a) {
count++;
a &= a - 1;
}
printf("%d", count);
}
Please help to solve this problem and explain the logic. I don't know how the & operator is working here.
void main() {
int a = -1;
static int count;
while (a) {
count++;
a &= a - 1;
}
printf("%d", count);
}
On
& is the bitwise and operator.
The operation
a&=a-1;
which is same as:
a = a & a-1;
clears the least significant bit of a.
So your program effectively is calculating the number of bits set in a.
And since count is declared as static it will automatically initialized to 0.
On
you have count uninitialized
should be
static int count=0;
operator & is called AND http://en.wikipedia.org/wiki/Bitwise_operation#AND
If you are referring to
then it is a bitwise and operation of a and a-1 copied into a afterwards.
Edit: As copied from Tadeusz A. Kadłubowski in the comment: