338. Counting Bits
来源:互联网 发布:知乎 江南七怪的实力 编辑:程序博客网 时间:2024/05/23 18:11
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.Show More Hint
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.
求0~num的数,每个数的二进制表示中分别有多少个1。
已经给提示了,2的幂次数1的个数只有1个,每次找出当前的数和哪个2的幂次最接近,把这个作为基数(其实就是1),
然后当前搜索数=(当前数-离当前数最近的2的幂次),这个当前搜索数一定在前面求出来了,直接加上就好。
public static int[] countBits(int num){int[] arr=new int[num+1];if(num<2){for(int i=0;i<=num;i++)arr[i]=i;return arr;}arr[0]=0;arr[1]=1;arr[2]=1;double lg2=Math.log10(2);for(int i=3;i<=num;i++){int power=(int) (Math.log10(i)/lg2);int base=(int) Math.pow(2, power);arr[i]=arr[base]+(i-base==0?1:arr[i-base]);}return arr;}
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
- MySQL 5.7 双主复制+keepalived,常规业务一般够用了
- 瀑布流UICollectionViewFlowLayout/UICollectionViewLayout
- Kotlin简单使用手册
- 黑马程序员_Java基础_我的Day26学习笔记
- React-native ListView 必须点击屏幕才会加载数据
- 338. Counting Bits
- webpack + vue.js + vue route
- MySQL索引原理及慢查询优化
- hibernate之关联映射
- error LNK2001: unresolved external symbol _IID_ISampleGrabberCB
- 交换两个变量的值
- Wifi模块——ESP8266(一)
- Linux中的可用内存指的是什么?
- PhotoShop教程:制作玻璃水晶质感文字