leetcode之Counting_Bits

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

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.
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.

题目如上,就是给你一个数字,让给输出从0到这个数字之间所有数字转化为二进制后1的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 0    0000    0                
// 1 0001 1
// 2 0010 1
// 3 0011 2
// 4 0100 1
// 5 0101 2
// 6 0110 2
// 7 0111 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
// 16 10000 1
// 17 10001 2

// 31 1 1111 5
// 63 11 1111 6

解法一:

1
2
3
4
5
6
7
8
var countBits = function(num) {
debugger
var res = [0]
for (var i = 1; i <= num; ++i) {
if (i % 2 == 0) res.push(res[parseInt(i / 2)])
else res.push(res[parseInt((i / 2))] + 1)
}
return res

解题思路:
从1开始,遇到偶数时,其1的个数和该偶数除以2得到的数字的1的个数相同,
遇到奇数时,其1的个数等于该奇数除以2得到的数字的1的个数然后再加上1
第二种思路:
1
2
3
4
5
6
7
var countBits = function(num) {
debugger
var res = [0]
for (int i = 1; i <= num; ++i) {
res[i] = res[i & (i - 1)] + 1;
}
return res

解题思路:每个i值都是i&(i-1)对应的值加1 (简单暴力,神奇的n与n-1)


第二种参考自Grandyangde的博客:


感觉不错的话给博主赞助一下呗