1: Evaluate the return value of the following function -- count the number of 1 ---- meaning of the x & (x-1) Expression
[Cpp]
Int func (int x)
{
Int countx = 0;
While (x)
{
Countx ++;
X = x & (x-1 );
}
Return countx;
}
Assume x = 9999
10011100001111
Answer: 8
Train of Thought: Convert x to a binary system and check the number of contained 1.
Note: each time x = x & (x-1) is executed, a 1 on the rightmost side of x is changed to 0 when x is represented in binary, because the X-1 will change this bit (A 1 on the rightmost when x is represented in binary) to 0.
2: Determine whether a number (x) is the N power of 2.
[Cpp]
# Include <stdio. h>
Int func (int x)
{
If (x & (x-1) = 0)
Return 1;
Else
Return 0;
}
Int main ()
{
Int x = 8;
Printf ("% d \ n", func (x ));
}
Note:
(1) If a number is the N power of 2, the highest bit of this number is 1 in binary format, and the rest is 0.
(2) = the priority is higher &
From the SongCdut Column