338. Counting Bits

来源:互联网 发布:校园青春网页网页源码 编辑:程序博客网 时间:2024/06/07 20:44

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].

思路:返回二进制中1的个数,可以借助已有的结果。ret[i] = ret[i >> 1] + (i & 1);

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



0 0
原创粉丝点击