【动态规划】Leetcode编程题解:338. Counting B 4000 its
2017-05-23 22:39
337 查看
题目: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.
样例:For
要求:
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.
观察每个数字的二进制表达,可以看到每个数字的二进制1的个数都是自己向左挪一位后所得到的数字1的个数加上自己本身最低位构成
代码:
i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
样例:For
num = 5you should return
[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.
观察每个数字的二进制表达,可以看到每个数字的二进制1的个数都是自己向左挪一位后所得到的数字1的个数加上自己本身最低位构成
代码:
class Solution { public: vector<int> countBits(int num) { vector<int> result(num + 1, 0); for(int i = 1; i <= num; i++) result[i] = result[i >> 1] + i % 2; return result; } };
相关文章推荐
- 【动态规划】Leetcode编程题解:70. Climbing Stairs
- 【动态规划】Leetcode编程题解:121. Best Time to Buy and Sell Stock Add to List
- 【动态规划】Leetcode编程题解:303. Range Sum Query - Immutable Add to List
- 【动态规划】Leetcode编程题解:198. House Robber Add to List
- leetcode -- 338. Counting Bits 【动态规划】
- 【动态规划】Leetcode编程题解:516. Longest Palindromic Subsequence Add to List
- [置顶] [编程题] LeetCode上的Dynamic Programming(动态规划)类型的题目
- 【动态规划】Leetcode编程题解:523. Continuous Subarray Sum Add to List
- LeetCode Arithmetic Slices(动态规划)
- 奖学金--动态规划--网易2016研发工程师编程题
- 【数组】Leetcode编程题解:495. Teemo Attacking
- LeetCode Scramble String(动态规划)
- 【动态规划】leetcode - Maximal Square
- 【LeetCode】010 番外篇 Dynamic Programming 动态规划
- [C++]LeetCode: 96 Maximum Product Subarray(动态规划)
- Leetcode 338. Counting Bits
- 年终奖(动态规划)---- 京东2016研发工程师编程题
- [算法作业-动态规划][LeetCode] 97. Interleaving String
- leetcode 312. Burst Balloons 气球爆炸计算分数 + 一个按照length做动态规划DP的很棒的做法
- LeetCode总结 -- 一维动态规划篇