您的位置:首页 > 其它

Leetcode 338. Counting Bits

2017-06-22 15:24 316 查看
题目·: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;
}
}
};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode