leetcode是求当前所有数的二进制中1的个数,剑指offer上是求某一个数二进制中1的个数

https://www.cnblogs.com/grandyang/p/5294255.html 第三种方法,利用奇偶性找规律 

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result{0};
        for(int i = 1;i <= num;i++){
            if(i % 2 == 0)
                result.push_back(result[i/2]);
            else
                result.push_back(result[i/2] + 1);
        }
        return result;
    }
};

 

 

 

class Solution {
public:
     int  NumberOf1(int n) {
         int count = 0;
         while(n){
             n = (n-1) & n;
             count++;
         }
         return count;
     }
};