Title:
An integer that indicates the number of output in the binary number 1. Wherein a negative number indicates a complement.
Problem-solving ideas:
If a non-zero integer, then this is an integer of at least 1. If we subtract the integer 1, then the original integer in the rightmost 1 will be changed to 0, the original becomes (0, then there's a 1 followed if the rightmost) 1 in all 01 will be back. All remaining bits will not be affected.
For example: a binary number
, starting from the first number on the right is in a rightmost
. minus
, the binary number becomes
, and then the original number of operation
, the result obtained
, so that we dealt with on the basis of a number of the original
, we make another such operation,
minus one
, get results
, and the number of the original
operation, the result obtained
, we found reduced
result is to put all the bits of the start of a rightmost 1 have taken backwards. This time the results after the original integer if we then do with the operation and subtract 1 from the original integer rightmost 1 the one who began all the bits will become 0. Such as the 1100 & 1011 = 1000. That put an integer minus 1, and then to do with the original integer arithmetic, the integer will rightmost 1 becomes 0. Then a binary integer of 1 how many, how much can be times such an operation.
code show as below:
int count=0,n;
class Solution {
public:
int NumberOf1(int n) {
int count =0;
while (n != 0)
{
count++;
n = n & (n - 1);
}
return count;
}
};