LeetCode 338. Counting Bits (Medium)

来源:互联网 发布:php chmod 777 编辑:程序博客网 时间:2024/05/17 14:20

题目描述:

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

Example:

num = 5 you should return [0,1,1,2,1,2].

题目大意:给出一个整数num,求0到num的所有数字的二进制形式的所有1的个数。(如5(101)含2个1)。

思路:把0-15的二进制形式写出来观察:

十进制 二进制 1的个数 0 00 0 1 01 1 2 10 1 3 11 2 4 100 1 5 101 2 6 110 2 7 111 3 8 1000 1 9 1001 2 10 1010 2 11 1011 3 12 1100 2 13 1101 3 14 1110 3 15 1111 4

观察,不妨把二进制的位数规定为1可能出现的最高位。那么可以给数字分组,比如0123是一组(2位),4567是一组(3位),8-15是一组(4位)。再观察可以得到:第n组数字是前n-1组所有对应数字扩展一位,并且那一位为1(相当于进位)。知道这个规律之后好做了:打表。

c++代码:

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