LeetCode解题报告 338. Counting Bits [medium]
来源:互联网 发布:原生js添加子节点 编辑:程序博客网 时间:2024/05/27 09:45
题目描述
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.
Hint:
- You should make use of what you have produced already.
- Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
- Or does the odd/even status of the number help you in calculating the number of 1s?
解题思路
题目意思就是将从0到给定的num的所有数字进行二进制表示后,计算每一个数字的二进制表示有多少个1,并输出成一个数组。同时提示不能用最无脑的办法算,要求O(n)的时间和空间复杂度。
在 hint提示中,有说划分成[2,3],[4,7][8,15]来找规律,列出表格如下:
可以看到,个数在上述三个区间内分别是12,1223,12232334。
比较容易发现奇数数字1的个数都是之前一个偶数数字1的个数加一,那么再继续寻找偶数数字和之前的数字有什么关系,题目中也提示使用之前已经计算出来的数字。
在二进制的最后一位加一个0,就相当于把这个数字乘2倍,类似十进制的末位加一个0,就是把这个数字乘10倍一样。
所以说,某个偶数数字和它的1/2大小的数字的二进制形式上就是末位多了一个0,那么1的个数是一样的。如6和3,14和7等。因此,用n/2的‘1’个数的结果来表示n的结果。
时间复杂度为O(n)
代码如下:
class Solution {public: vector<int> countBits(int num) { vector<int>result(num+1,0); for (int i=1; i<=num; i++) { if (i%2==0) { result[i]=result[i/2]; } else{ result[i]=result[i-1]+1; } } return result; }};
0 0
- LeetCode解题报告 338. Counting Bits [medium]
- [leetcode] 338. Counting Bits 解题报告
- LeetCode 338.Counting Bits 解题报告
- leetcode解题报告:338. Counting Bits
- [Leetcode] 338. Counting Bits 解题报告
- 【LeetCode】Counting Bits 解题报告
- LeetCode 338. Counting Bits (Medium)
- 338.LeetCode Counting Bits(medium)[二进制位处理]
- Leetcode 338. Counting Bits (Medium) (cpp)
- 【leetcode】【Medium】【338. Counting Bits】【规律】
- 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---Counting Bits解题分析
- Performance Modeling
- 第八周—显示数字图形
- (Unicode) UTF-8与UTF-16之间转换
- Android 沉浸式状态栏实现及细节处理
- Kali 2016 rolling版open-vm-tools
- LeetCode解题报告 338. Counting Bits [medium]
- 控制<a></a>标签不在跳转的方法
- hdoj-【2089 不要62】
- OpenCV学习笔记(2)
- LinkedHashMap源码理解
- DOM 0级事件和DOM2级事件的认识
- EventBus的使用详解
- Android横竖屏切换界面不重启
- 库函数和系统调用的区别