LeetCode 338 Counting Bits (递推)
来源:互联网 发布:pptv网络电视播放器 编辑:程序博客网 时间:2024/06/06 20:27
Given a non negative integer number num. For every numbersi 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 timeO(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.
题目链接:https://leetcode.com/problems/counting-bits/
题目分析:直接递推即可,若当前数字是奇数,其二进制中1的个数相当于它右移一位的那个数中1的个数加1,偶数则不加1
public class Solution { public int[] countBits(int num) { int[] dp = new int[num + 1]; Arrays.fill(dp, 0); dp[0] = 0; for(int i = 1; i <= num; i ++) { dp[i] += dp[i >> 1] + (i & 1); } return dp; }}
0 0
- LeetCode 338 Counting Bits (递推)
- leetcode:bits:Counting Bits(338)
- 【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
- Counting Bits leetcode 338
- [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
- Git学习(六)
- 四大应用组件之Service【Android】
- Shader例子博客
- iOS - Masonry简介及使用(very good)
- Git 入门
- LeetCode 338 Counting Bits (递推)
- Django模板语言
- js动态加载列表
- android 应用中去掉标题栏的几种方法
- java assert
- JAVA发送http get/post请求,调用http接口、方法
- QString 转 BSTR
- 详解Dagger2
- android开发小tips