338. Counting Bits

来源:互联网 发布:云像数字 知乎 编辑:程序博客网 时间:2024/05/17 07:32

题目描述:

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.
解题思路:

本题要我们列出从0到num的二进制表示中1的个数,通过观察我们可以知道,当偶数i加上1时,1的个数也加1,但当奇数i加上1时,由于进位,1的个数可能不变甚至减少。我们先假设每个数的1的个数都在上一个数的基础上加1,那么当这个数为偶数时,1的个数要减去1,并且右移一位,直到这个数不再是偶数。

代码:

class Solution {public:    vector<int> countBits(int num) {        vector<int> bits(num+1, 0);        for (int i = 1; i <= num; i++) {            int temp = i;            bits[i] = bits[i-1] + 1;            while (temp % 2 == 0) {                bits[i] -= 1;                temp /= 2;            }        }        return bits;    }};

原创粉丝点击