【LeetCode】 338. Counting Bits
来源:互联网 发布:知乎 进小区发传单 编辑:程序博客网 时间:2024/06/05 02:41
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?
public class Solution { public int[] countBits(int num) { int[] res = new int[num + 1]; for (int i = 0; i <= num; i++) { res[i] = Integer.bitCount(i); } return res; }}
public class Solution { public int[] countBits(int num) { int result[] = new int[num + 1]; int offset = 1; for (int index = 1; index < num + 1; ++index){ if (offset * 2 == index){ offset *= 2; } result[index] = result[index - offset] + 1; } 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
- Oracle Hash分区的使用总结
- 复合分区 (范围-散列分区,范围-列表分区)
- 需求管理
- 深入oracle分区索引的详解
- Oracle 分区表维护
- 【LeetCode】 338. Counting Bits
- Windows下Tensorflow安装流程
- 205. Isomorphic Strings
- C语言计算日期,前n天,后n天方法
- 80老翁谈人生(314):别了,亲爱的CSDN读者朋友们!
- 【LeetCode】 413. Arithmetic Slices
- Amazon EC2 Instance Express API配置HTTPS
- ZCMU-1787-Babelfish
- Erlang 实现互斥量