LeetCode-Counting Bits

来源:互联网 发布:json在线处理 编辑:程序博客网 时间:2024/06/16 01:28

1. Counting Bits (Medium)

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

Analysis

i binary num of ‘1’ i&(i-1) 0 0000 0 1 0001 1 0000 2 0010 1 0000 3 0011 2 0010 4 0100 1 0000 5 0101 2 0100 6 0110 2 0100 7 0111 3 0110 8 1000 1 0000 …… …… …… ……

我们可以发现每个i值都是i&(i-1)对应的值加1,这样我们就可以写出代码如下:

代码:

class Solution {public:    vector<int> countBits(int num) {        vector<int> result(num + 1, 0);        for (int i = 1; i <= num; ++i) {            result[i] = result[i & (i - 1)] + 1;        }        return result;    }};
原创粉丝点击