Please help to solve this problem and explain the logic. I don't know how the & operator is working he开发者_StackOverflow中文版re.
void main() {
int a = -1;
static int count;
while (a) {
count++;
a &= a - 1;
}
printf("%d", count);
}
If you are referring to
a&=a-1;
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:
a = a & (a-1);
The expression a&=a-1; clears the least significant bit (rightmost 1) of a. The code counts the number of bits in a (-1 in this case).
Starting from
a = -1 ; // 11111111 11111111 11111111 11111111 32bits signed integer
The code outputs 32 on an 32 bit integer configuration.
& 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.
you have count uninitialized
should be
static int count=0;
operator & is called AND http://en.wikipedia.org/wiki/Bitwise_operation#AND
加载中,请稍侯......
精彩评论