leetcode brush series title

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 1111 1111 , starting from the first number on the right is in a rightmost 1 1 . minus 1 1 , the binary number becomes 1110 1110 , and then the original number of operation 1111 & 1110 1111\&1110 , the result obtained 1110 1110 , so that we dealt with on the basis of a number of the original 1 1 , we make another such operation, 1110 1110 minus one 1 1 , get results 1101 1101 , and the number of the original 1110 1110 operation, the result obtained 1100 1100 , we found reduced 1 1 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;
     }
};

Guess you like

Origin blog.csdn.net/weixin_43615373/article/details/90416637