<LeetCode OJ> 338. Counting Bits
来源:互联网 发布:做班服的软件手机 编辑:程序博客网 时间:2024/05/17 04:52
题目翻译:
给定一个非负整数Num。每一个数字i均在范围0≤i≤Num,计算每一个i二进制中1的个数,存放在数组中返回。
例子:
num = 5
你应该返回[ 0,1,1,2,1,2 ]
。
要求:
- 一个运行时间为O(n * sizeof(integer))的解决方案很容易。但你能在线性时间O(N)解决问题吗?
- 空间复杂度应该O(N)。
- 不使用任何内建函数
提示:
- 你应该充分利用你已经计算出来的结果(赶紧想到动态规划)。
分析:DONE
直接用stl中的位类来做。
class Solution {public: vector<int> countBits(int num) { vector<int> result; for(int i=0;i<= num;i++) { bitset<32> cntbit(i); result.push_back(cntbit.count());//count()函数统计二进制中1的个数 } return result; }};
或者:
class Solution {public: vector<int> countBits(int num) { vector<int> result; for (int i = 0; i <= num; ++i) { int curnum = i, cnt = 0; while (curnum) { if (curnum&0x0001) //判断对应二进制数中最右边是否为1 ++cnt; curnum = curnum>>1; //削掉对应二进制数中最右边的1 } result.push_back(cnt); } return result; }};
学习别人的算法:动态规划
可以从每个数的最低位开始分析,例如1001001 ,它的二进制1的个数等于100100 总二进制个数 + 1 。
即 f = f/2 + (f 的最低位)
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&1; return result; }};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50986178
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895
1 0
- <LeetCode OJ> 338. Counting Bits
- LeetCode OJ-338.Counting Bits
- LeetCode oj 338. Counting Bits(DP)
- leetcode oj java Counting Bits
- [leetcode] 338. Counting Bits
- leetcode 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- (leetcode) 338. Counting Bits
- #leetcode#338. Counting Bits
- LeetCode 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCode-338. Counting Bits
- Android 轻量级轮播组件 CycleViewPager
- java,二进制转换为十进制,valueof和parseInt的区别
- 集合第五发TreeSet和TreeMap
- POJ 1177 Picture(矩形并的周长)
- 从setcontentView说起----Android的Windows
- <LeetCode OJ> 338. Counting Bits
- HDU 1255 覆盖的面积(矩形交的面积)
- COCI 2011/2012 Contest#2(TOJ4484 FUNKCIJA)
- POSIX标准总体分析
- leetcode 2. Add Two Numbers
- 捎带确认
- 第六届CCF计算机职业资格认证考试题解(C++)
- 字符串
- 对this的浅显的理解