9- prove safety offer: the number of binary 1

Title Description

An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.

Code

class Solution {
public:
     int  NumberOf1(int n) {
         if(n==0) return 0;
         // 每次清除一位的0
         int cnt=0;
         while(n) {
             n = n&(n-1);
             cnt++;
         }
         return cnt;
     }
};

Minus 1, then the original data will result in a 1 on becomes 0, and direct access to the action position 0.

Guess you like

Origin www.cnblogs.com/xl2432/p/10930108.html