LeetCode P338 Counting Bits 题解
1.题目:
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.
题意:
输入一个数字num
返回一个数组
这个数组是0至num中所有数字的二进制表达中有几个1
希望空间复杂度和时间复杂度不超过O(n)
2.解题思路:
先写出前几个数的二进制进行分析:
0 0 0
1 1 1
2 10 1
3 11 2
4 100 1
5 101 2
…
首先我们可以知道2的n次方的二进制中1的个数都是1
其次在这个基础上分析 其它的数a=小于a的最大二进制数b+(b-a)
则它的二进制中1的个数=1+n(b-a)
3.代码
1 |
|
4.一些总结:递推思想,还有很多更有趣更奇妙的解法~待续