This is a creation in Article, where the information may have evolved or changed.
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 you num = 5 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 I do it in linear time O (n) /possibly in a single pass?
- Space complexity should be O (n).
- Can do it like a boss? Do it without the using any builtin function like __builtin_popcount in C + + or any other language.
The main idea is, given a non-negative integer num, returns the number of binary representations from 0 to num of 1 Here is my implementation, submit to Leetcode on show run time timeout The idea is this: numbers: 0 1 2 3 4 5 6 7 8 9 Ten 1 Numbers: 0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4 1 2 2 3 Here you can see the law, the number 4 5 6 7 of the number of 1 must be the number 0, 1 2, 3, and 1, the same number 1 8 9 10 11 12 13 14 The number of 15 must be the number 1 0 1 2 3 4 6 7 of 1 of the number plus 1, then it seems to follow this method can achieve linear time complexity
Func countbits (num int) []int { if num = = 0 { return []int{0} } if num = = 1 { return []int{0, 1} } arr: = Make ([]int, num + 1) arr[0] = 0 arr[1] = 1 J: = 0 Lastturn: = 2; For I: = 2; I <= num; i++ { Arr[i] = arr [j] + 1 j + + if j = = Lastturn { j = 0 Lastturn = i + 1 } } retur N arr}
Using the online recommendation of the fast algorithm, still time-out, the principle of fast algorithm is n& (n-1), each time the operation is performed, you can remove the lowest bit of n 1, then the number of times the operation needs to be executed to change N to 0, which is the number of n 1, the algorithm in a single operation has advantages, But it doesn't look good in this time.
Func countbits (num int) []int { arr: = Make ([]int, num + 1) for I: = 0; I <= num; i++ { sum: = 0 N: = i for ; n! = 0; sum++ { n = n & (n-1) } arr[i] = sum } return arr}
There is another algorithm, but still can not pass, unscientific ah, I see others in other languages are written like this can pass
Func countbits (num int) []int { arr: = Make ([]int, num+1) for i: = 1; i <= num; i++ { Half: = i >> 1< C3/>if I% 2 = = 0 { Arr[i] = arr[half] } else { arr[i] = arr[half] + 1 } } return arr}