Prove safety offer-- binary number 1 (c ++)

Description Title
implement a function, an integer input, the output binary number represents the number 1.
For example, to 9 is expressed as a binary 1001, the output is 2

Conventional Solution
First to n and 1-bit computing to do, determine the lowest bit of n is not 1, then the left one get 2 1, then 2, and n-bit computing to do, judge of n times so low is not repeated 1 ... left.
Number of cycles equal to the number of bits of binary integer, 32-bit integer requires 32 cycles.

{Solution class
int NumberOfOne (n-int) {
int CNT = 0;
unsigned int In Flag =. 1;
the while (In Flag) {
IF (n-In Flag &) {
++ CNT;
}
In Flag In Flag = <<. 1;
}
return CNT;
}
};
1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
13 is
a surprise solution
to a subtracting the integer 1, and in doing integer arithmetic and original, which will become an integer of 0 rightmost.
Then the binary representation of an integer in the number of 1, on how many times such an operation can be performed.
To 1100, for example, it is the result of subtracting 1, 1011, then 1100 and 1011 bit and do arithmetic, the result is 1000,
then 1000 minus 1, to obtain 0111, and 1000-bit and do arithmetic, the result is 0000, 1100 to give it a two.

class Solution {
int NumberOfOne1(int n){
int cnt = 0;
while(n){
++cnt;
n = (n - 1) & n;
}
return cnt;
}
};
1
2
3
4
5
6
7
8
9
10

---------------------

Guess you like

Origin www.cnblogs.com/ly570/p/11109351.html