Leetcode 338. Counting Bits
来源:互联网 发布:工行信用卡 知乎 编辑:程序博客网 时间:2024/04/26 17:54
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~num 的每个数的二进制中包含的1的个数的计算,0的二进制中的1为0个,之后的计算,考虑两种情况:
1)该为是2的幂次方,则二进制只包含一个1
2)该位不是2的幂次方,则二进制的位数 = 比该位数字小,且最接近的2的幂次方的1的个数+(该位数值-比该位数字小,且最接近的2的幂次方的数)的数的1的个数
具体代码如下:
public class Solution { public int[] countBits(int num) { int[] result = new int[num+1]; result[0] = 0; int flag = 0;//标记上一个2的次幂的位置 int pow =1; for(int i = 1; i < num+1; i++){ if(i == pow){ pow *= 2; result[i] = 1; flag = i; } else{ result[i] = result[flag]+ result[i-flag]; } } return result; }}
0 0
- [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-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-338. Counting Bits
- leetcode-338. Counting Bits
- Leetcode 338. Counting Bits
- LeetCode 338. Counting Bits
- Java多线程系列--“JUC集合”01之 框架
- iOS学习笔记77-ios开发,javascript直接调用oc代码而非通过改变url回调方式
- Prototype使用$F()函数
- 策略模式(行为型)
- php trait
- Leetcode 338. Counting Bits
- java Swing布局管理器之FlowLayout布局
- Prototype使用$w()函数
- iOS后台持续播放音乐
- 数据结构与算法——递归简论
- 专题三1011
- Java super语句
- 第15章 就不能换DB吗?—抽象工厂模式
- UVA 10829 L-Gap Substrings