Prove safety offer 11: 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.
Solution a: setting a flag to flag = 1, by one bit to a different location, whether the comparison is 1.
C ++ implementation
class Solution {
public:
     int  NumberOf1(int n) {
         unsigned int flag=1;
         int count=0;
         while(flag!=0){
             if(n&flag){
                 count++;
             }
             flag=flag<<1;
         }
         return count;
     }
};

  

Solution two: an integer minus 1, and then to do with the original number of operations, you can eliminate a 1 at the far right, successive elimination, until the number becomes zero.
class Solution {
public:
     int  NumberOf1(int n) {
         int count=0;
         while(n!=0){
              count++;
              n = n & (n-1);   
          }
         return count;
     }
};

  

Guess you like

Origin www.cnblogs.com/fancy-li/p/11612324.html