338. Counting Bits
来源:互联网 发布:造价大师预算软件 编辑:程序博客网 时间:2024/06/13 10:46
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].
要求O(n)时间
巧妙的利用了i&(i - 1), 这个本来是用来判断一个数是否是2的指数的快捷方法,比如8,二进制位1000, 那么8&(8-1)为0,只要为0就是2的指数, 那么我们现在来看一下0到15的数字和其对应的i&(i - 1)值:
i bin '1' i&(i-1) 0000 0----------------------- 0001 1 0000----------------------- 0010 1 0000 0011 2 0010----------------------- 0100 1 0000 0101 2 0100 0110 2 0100 0111 3 0110----------------------- 1000 1 0000 1001 2 1000 1010 2 1000 1011 3 1010 1100 2 1000 1101 3 1100 1110 3 1100 1111 4 1110
class Solution {public: vector<int> countBits(int num) { vector<int> res(num + 1, 0); for (int i = 1; i <= num; ++i) { res[i] = res[i & (i - 1)] + 1; } return res; }};
0 0
- [leetcode] 338. Counting Bits
- 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCodeOJ:338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- 338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- 338. Counting Bits
- (leetcode) 338. Counting Bits
- Swift 338. Counting Bits
- #leetcode#338. Counting Bits
- LeetCode 338. Counting Bits
- 【机器学习】【读后感】(条件)概率模型们的本质:树状、时序到一般性的图
- 在 OC 中实现消息的转发
- php安装解析
- poj 3274 哈希查找(黄金平衡)
- [Lintcode]Valid Parentheses
- 338. Counting Bits
- Spring 注解总结
- KindEditor编辑器的使用
- ValueAnimator的使用
- PLSQL Developer连接数据库报错ora-12514解决
- maven---私服
- 算法题之查找第一个只出现一次的字符
- 练习005
- Android APP头像的图标与背景的设置