LeetCode #338: Counting Bits

Problem

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

*Follow up: **
It is very easy to come up with a solution with run time O(n
sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Solution

题意

任意给一个数字n,要求算出0,...,n每个数字的二进制表示中一的个数,结果存储在一个vector里。

分析

  1. 这道题一个时间复杂度为O(n*sizeof(int))的解法在另一道题——LeetCode #461: Hamming Distance——里也出现过,即,对数字i进行二进制移位操作,每次右移一位,然后与1求与,如果结果为1,则表示移位后的数字最低有效位为1。重复该操作,直到遍历i的所有二进制位(即循环的条件是i == 0)。
  2. //TODO

Code - Version1

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result;
        for (int i = 0; i <= num; i++){    //遍历0到num的所有数字
            int count = 0;
            for (int j = i; j; j >>= 1){    //遍历i的所有二进制位
                if (j & 1)    //j&1的结果为1则表示j的最低位为1,否则为0
                    count ++;
            }
            result.push_back(count);
        }
        return result;
    }
};

Code - Version2

//TODO
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • Given a non negative integer number num. For every number...
    Eazow阅读 495评论 0 0
  • 有人告诉我, 今日大寒 一年中最后一个节气 我想起 三月春风明媚的午后 一个长长的电话泛起的清澈涟漪 已经是一个寒...
    王不烦阅读 165评论 0 0
  • 入梦夜阑深, 不足惊中起。 和衣遣其能, 笔下徒憾生。 平素少梦,乐其难得,仍有感于弗洛伊德之《解析》,聊以自娱。...
    汪汪的喵阅读 322评论 0 0
  • 家里的冰箱坏了好久了,然而老妈也没有要换的意思。有时候我顶着个烈日,跑到商场一手抓起一堆雪糕,一手拿着袋子往里面塞...
    林里叶落阅读 418评论 1 3