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;
}
}
};
。
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 338. Counting Bits
- LeetCode 338. Counting Bits
- LeetCode 338. Counting Bits
- Leetcode 338. Counting Bits
- LeetCode 338. Counting Bits
- [LeetCode] 338. Counting Bits
- leetcode 338. Counting Bits
- leetcode 338. Counting Bits
- 【LeetCode】338. Counting Bits
- [leetcode] 338. Counting Bits
- leetcode 338. Counting Bits
- Leetcode 338. Counting Bits (Medium) (cpp)
- leetcode 338. Counting Bits
- (leetcode) 338. Counting Bits
- 【leetcode】338. Counting Bits
- LeetCode 338. Counting Bits
- leetcode 338. Counting Bits
- [leetcode]: 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCode 338. Counting Bits