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

Idea: Find the pattern in this sequence

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> r = vector<int>();
        r.reserve(num+1);
        r.push_back(0); // non negative int
        if(num == 0) return r;
        r.push_back(1); 
        if(num == 1) return r;
        
        for(int p1=1,p2=2;r.size() <= num;p1*=2,p2*=2){
            for(int j=p1;j<p2 && r.size() <= num;j++) r.push_back(r[j]);
            for(int j=p1;j<p2 && r.size() <= num;j++) r.push_back(r[j] + 1);
        }
        return r;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,364评论 0 33
  • 一、产品简介 TunesGo for Mac是 Wondershare面向海外发布的一款苹果手机设备付费管理软件。...
    渡边不纯阅读 4,059评论 0 1
  • 上了彭小六的知识管理训练营,知道了快速阅读这一利器。1个小时读完一本书,多爽啊。 适用边界 首先,速读的书适用于实...
    懒虫子的美丽人生阅读 3,047评论 3 3
  • 看到一篇关于自律的文章,深深的震撼了,厉害的人从来都是自律的,没有任何借口和理由去编织谎言 说到为什么要自律? 1...
    易槿槿阅读 1,850评论 0 0

友情链接更多精彩内容