[Medium] Counting Bits
来源:互联网 发布:mac在哪里新建文件夹 编辑:程序博客网 时间:2024/06/05 03:14
【问题】
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.
【解法】
观察二进制数的规律可以知道。对于从0~2^n-1这2^n个数组成的数列a[],可以知道,前2^(n-1)个数的最低(n-1)位,与后2^(n-1)个数(n-1)位具有相同的发展规律,不同的是前2^(n-1)个数最高位是0,后2^(n-1)个数最高位为1.
由此,可以知道,对于从0~2^n-1这2^n个数组成的数列,取i=2^(n-1),2^(n-1)+1,...,2^n - 1。对于第i个数a[i],其‘1’的个数是第i-2^(n-1)个数a[i-2^(n-1)]加一。这两个数的区别仅在于最高位,前者为1,后者为0.
【源码】
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
int n = 2;
res.clear();
res.push_back(0);
res.push_back(1);
while (n - 1 < num) {
for (int i = 0; i < n; ++i) {
res.push_back(res[i] + 1);
}
n = n * 2;
}
res.resize(num + 1);
return res;
}
};
- 338. Counting Bits #Medium
- [Medium] Counting Bits
- [Medium]Counting Bits
- 338. Counting Bits -Medium
- 338. Counting Bits-medium
- 338. Counting Bits [medium] (Python)
- Medium 338题 Counting Bits
- leetcode338:Counting Bits(medium)
- 338. Counting Bits 难度:medium
- Leetcode #338 - Counting bits - Medium
- LeetCode 338. Counting Bits (Medium)
- 338.LeetCode Counting Bits(medium)[二进制位处理]
- Leetcode 338. Counting Bits (Medium) (cpp)
- Counting Bits——Difficulty:Medium
- LeetCode解题报告 338. Counting Bits [medium]
- 【leetcode】【Medium】【338. Counting Bits】【规律】
- Leet Code OJ 338. Counting Bits [Difficulty: Medium]
- 动态规划——338. Counting Bits[Medium]
- C++11并发/多线程编程系列(2)
- Lua(下)
- Nginx事件模块init
- 无废话WCF入门教程四[WCF的配置文件]
- 安卓热修复,android打补丁,不用发版本就能实时的解决一些线上版本的bug
- [Medium] Counting Bits
- react-redux-react-router直通车
- Node.js开发的WeMall 6.0正式发布
- 【排序】堆排序实现
- css排版之float浅析
- 无废话WCF入门教程五[WCF的通信模式]
- Redis主从之从Redis服务器Key不失效
- 滑动插件scroll.js
- json数据如何存入到cookie中,如何获取