Preface
will be writing some regular interview questions recently, the test will share with you after the
Displacement Method
is only suitable for positive numbers:
The
shift method is to determine whether the minimum bit of n is 1, and the time complexity is O (logn)
Copy Code code as follows:
int nativeonenum (int n)
{
int count = 0;
while (n) {
if (n & 1) count + +;
n >>= 1;
}
return count;
}
is no problem for positive numbers, but if n is negative, here's the problem, with negative 8 as an example, the binary complement form is 11111111|11111111|11111111|11111000|, and the right one becomes the 11111111|11111111 |11111111|11111100|, because it is a negative number, so the sign bit will continue to fill 1, resulting in the last 1, the death cycle
in this case, we can use the variable flag = 1, from right to left and n comparison, 32-bit int up to 32 times to know the number of n 1
Copy Code code as follows:
int onenum (int n)
{
int count, flag;
for (count = 0, flag = 1; flag; flag <<= 1) {
if (flag & N) count + +;
}
return count;
}
Rapid Method
This solution is that the number of binary 1 is only related to 1 of the number of digits, N & (n-1) quickly remove the leftmost 1, such as 7 (0111) & 6 (0110) = 6 (0110), quickly remove the leftmost 1
Copy Code code as follows:
int quickone (int n)
{
I NT count = 0;
while (n) {
; Count ++;
n = n & (n-1);
&nbs p; }
return count;
}