#leetcode#338. Counting Bits
2016-04-11 21:47
369 查看
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
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.
研究规律
位运算
与
与或
class Solution {
public:
vector<int> countBits(int num) {
vector<int> cc(num+1,0);
int i;
for(i=1;i<=num;i++)
cc[i]=cc[i>>1]+i%2;
return cc;
}
};
return them as an array.
Example:
For
num = 5you 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.
研究规律
位运算
与
与或
class Solution {
public:
vector<int> countBits(int num) {
vector<int> cc(num+1,0);
int i;
for(i=1;i<=num;i++)
cc[i]=cc[i>>1]+i%2;
return cc;
}
};
相关文章推荐
- 关于举办大数据处理技术培训的通知
- “大数据分析高级工程师”培训
- 求解路由路径问题(华为挑战赛小思)
- 模拟printf函数,//print("val:s ccccc\n","hello", 'w,'o','r','l','d'); //val:hello world(可变参数列表)
- Java入门 第一季第四章 流程控制语句
- c++第三次实验
- 关于举办大数据处理技术培训的通知
- “大数据分析高级工程师”培训
- H5 优化
- Android自定义组件系列【17】——教你如何高仿微信录音Toast
- 关键概念
- CodeForces580B
- 在dos命令行输入adb shell命令时出现错误的解决方案
- 成都大数据Hadoop与Spark技术培训班
- Android自定义组件系列【17】——教你如何高仿微信录音Toast
- Eular质数筛法-hiho一下 第九十三周
- ListView中的数据一直显示在最底部(类似聊天中的信息列表)
- IOS百度地图定位总结
- 27. Remove Element
- 成都大数据Hadoop与Spark技术培训班