leetcode014-Counting Bits
来源:互联网 发布:中科汇通知乎 编辑:程序博客网 时间:2024/06/09 14:36
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.
解题思路:动态规划,dp[i]代表数字i的二进制含有多少个1
如果i是奇数的话,i-1是偶数,那个i-1的二进制的最低位一定是0,加1并不会进位,所以dp[i] = dp[i-1]+1
如果i是偶数的话,i会与i/2的二进制拥有相同个数的1,因为i/2左移一位,最后补0,就是i,所以dp[i] = dp[i/2]
class Solution {public: vector<int> countBits(int num) { vector<int> dp(num+1,0); for (int i = 1; i <= num; i++) { if (i%2==0) { dp[i] = dp[i/2]; } else { dp[i] = dp[i-1]+1; } } return dp; }};
阅读全文
0 0
- leetcode014-Counting Bits
- leetcode014
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- 疯狂Activiti6.0连载(27)BPMN中间事件
- UFLDL 教程学习笔记:3.预处理-主成分分析与白化
- Kotlin-1.2-包和导入
- shell 脚本调试
- Microsoft OneNote 2016 for Mac (云笔记) 含OneNote激活工具 v15.14中文破解版
- leetcode014-Counting Bits
- eclipse 中使用git插件
- python 的继承和多态
- Cassandra压实(一)
- java学习笔记(一)——对象
- 第一次开通博客
- 在Java的Set集合中放入自定义类
- 基于Docker的微服务架构-企业级服务集群实践(一)
- 《java8函数式编程》第三章课后习题