1. 程式人生 > >LeetCode 338. Counting Bits

LeetCode 338. Counting Bits

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.

Example:
For num = 5 you should return [0,1,1,2,1,2].

分析:這是一道對於位運算的題目。迭代公式為
dp[i]=dp[i>>1]+(i&1)
比如4(100),它是由2(10)在末尾添加個0,5(101)是2(10)在末尾添加個1。
程式碼如下:

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