[leetcode]338. Counting Bits

[leetcode]338. Counting Bits


Analysis

周五ummmmmm—— [啊啊啊啊 paper结果要出来了,心塞]

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
找规律的题目,这里解释的比较清楚:http://www.cnblogs.com/grandyang/p/5294255.html

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81394014
今日推荐