338. Counting Bits
来源:互联网 发布:情义我心知 电影 2005 编辑:程序博客网 时间:2024/06/06 20:17
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.
题目的要求是给定一个整数num,在0<=i<=num的范围内,求每个整数的二进制表示中1的个数,并以数组的形式返回结果。这道题目按照正常的解题思路去解决非常简单,但是复杂度不够理想,题目希望我们可以相处复杂度为O(n)的解法。
既然通过O(n)的算法可以解决,那么必然存在某种规律性:
数字 二进制 1的个数0 0000 01 0001 12 0010 13 0011 24 0100 15 0101 26 0110 27 0111 38 1000 1
有一个显然的事实就是,只要是2的指数,1的个数都是1。至于其他数字,我们可以发现,每个数字1的个数,都是数字i&(i-1)中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&(i-1)] + 1; } return result; }};
阅读全文
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
- 求1000以内的回文素数(爱奇艺)
- 【视频开发】视频质量诊断之详解
- 没有wifi的童年,我们是这样过的
- 做对三件事,你也能像聪明人一样高速成长!【文末有福利】
- Keil 下生成LIB库文件以及如何使用LIB库文件
- 338. Counting Bits
- veu项目中引入jquery
- PL/SQL之七 动态SQL
- null和undefined
- GitHub上README.md教程
- java.util.List.subList分析
- 【攻略·转载·收藏】手把手教程 | 申请签证很难吗?靠你自己就能搞定!(以英国签证为例)
- CCS6.2.0下加载C6748的GEL文件
- 安全性