Leetcode 338. Counting Bits

来源:互联网 发布:arcgis api for js 编辑:程序博客网 时间:2024/06/03 17:27

题目·: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.

思路:对于前n为的数如果已经统计了,假设结果保存在vector<int> re里面,那第n+1为所对应的应该为re[0~end]依次加一。比如三位的数,每个前面加上个1就可以组成第四位的;第二位的数第三位为0,第一位为1页是组成第四位的。依次相加,直到结果数为num+1为止。

class Solution {public:    vector<int> countBits(int num) {        vector<int> re;        int count1=1;        re.push_back(0);        while(1){            if(re.size()==num+1) return re;            for(int i=0;i<=count1-1;i++) {                re.push_back(re[i]+1);                if(re.size()==num+1) return re;            }            count1*=2;        }    }};

原创粉丝点击