LeetCode 338. Counting Bits (Medium)
来源:互联网 发布:php chmod 777 编辑:程序博客网 时间:2024/05/17 14:20
题目描述:
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.
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.
Example:
num = 5 you should return [0,1,1,2,1,2].
题目大意:给出一个整数num,求0到num的所有数字的二进制形式的所有1的个数。(如5(101)含2个1)。
思路:把0-15的二进制形式写出来观察:
观察,不妨把二进制的位数规定为1可能出现的最高位。那么可以给数字分组,比如0123是一组(2位),4567是一组(3位),8-15是一组(4位)。再观察可以得到:第n组数字是前n-1组所有对应数字扩展一位,并且那一位为1(相当于进位)。知道这个规律之后好做了:打表。
c++代码:
class Solution {public: vector<int> countBits(int num) { vector<int> ans; ans.push_back(0); ans.push_back(1); ans.push_back(1); ans.push_back(2); while (ans.size() < num + 1) { int o_size = (2 * ans.size()) > (num + 1) ? num + 1 - ans.size() : ans.size(); for (int i = 0; i < o_size; i++) { ans.push_back(ans[i] + 1); } } while (ans.size() > (num + 1)) { ans.pop_back(); } return ans;}};
阅读全文
0 0
- LeetCode 338. Counting Bits (Medium)
- 338.LeetCode Counting Bits(medium)[二进制位处理]
- Leetcode 338. Counting Bits (Medium) (cpp)
- LeetCode解题报告 338. Counting Bits [medium]
- 【leetcode】【Medium】【338. Counting Bits】【规律】
- 338. Counting Bits #Medium
- 338. Counting Bits -Medium
- 338. Counting Bits-medium
- Leetcode #338 - Counting bits - Medium
- 338. Counting Bits [medium] (Python)
- 338. Counting Bits 难度:medium
- [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-43-Multiply Strings 模拟
- Ambari安装之部署单节点集群
- 使用Unity3D制作技能图标冷却效果
- Spring的bean的生命周期
- Appserv连接Mysql失败解决方式
- LeetCode 338. Counting Bits (Medium)
- ionic+做一个侧滑跳转+标题头旁边有一个后退功能的按钮
- Ambari安装之部署3个节点的HA分布式集群
- LintCode 488快乐数
- centos6.5编译安装php7
- Bootstrap carousel轮播图插件 简洁版
- Service层getParameter方法接受字符转换成int类型
- SQLServer代理电脑重启每次都需要手动开启服务的解决方案
- 关于中医医院CRM客户关系管理系统构建的研究分析