题目描述

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 1:

 1 2 Input: 2 Output: [0,1,1]

Example 2:

 1 2 Input: 5 Output: [0,1,1,2,1,2]

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.

解题思路

$$f(N) = f(N/2) + (S(N) == 1)$$ $$…$$ $$f(0) = 0$$

 1 2 3 4 5 6 7 8 def count_bit(N): if N == 0: return 0 if N & 1 == 1: return count_bit(N/2) + 1 else: return count_bit(N/2)

代码

• solution.go
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package l338 func CountBits(num int) []int { var result []int var bitCount int result = append(result, 0) for i := 1; i <= num; i++ { if i&1 == 1 { bitCount = result[i>>1] + 1 } else { bitCount = result[i>>1] } result = append(result, bitCount) } return result }
• solution_test.go
 1 2 3 4 5 6 7 8 9 10 11 12 13 package l338 import ( "testing" "github.com/stretchr/testify/assert" ) func TestCountBits(t *testing.T) { assert.Equal(t, []int{0, 1, 1}, []int{0, 1, 1}) assert.Equal(t, CountBits(2), []int{0, 1, 1}) assert.Equal(t, CountBits(5), []int{0, 1, 1, 2, 1, 2}) }