本文主要是介绍338. Counting Bits【M】【leetcode题解】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.
Show Hint
-
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
它是有规律地重复的
class Solution(object):def countBits(self, num):if num == 0:return [0]res = [0]bit = 0temp = numwhile temp > 0:temp /= 2bit += 1#print bitfor i in xrange(bit-1):t_res = []for j in res:t_res.append(j+1)res = res + t_res#print resfor i in res[:(num - pow(2,bit-1))+1]:res.append(i+1)return res
这篇关于338. Counting Bits【M】【leetcode题解】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!