LeetCode 338 Counting Bits (递推)

原创 2016年08月30日 16:23:04

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.

题目链接: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;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

[leetcode]--338. Counting Bits

Question 338. Counting Bits Question: Given a non negative integer number num. For every numbers i...

Leetcode #338 - Counting bits - Medium

ProblemGiven a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calcula...
  • Arcome
  • Arcome
  • 2016年10月25日 17:46
  • 185

Leetcode 338. Counting Bits

338. Counting Bits Total Accepted: 23381 Total Submissions: 41506 Difficulty: Medium Given a ...

leetcode338:Counting Bits(medium)

经过一年的雁栖学习,终于回到了实验室,开始了研二的科研生活,是时候把我这一年的所学所想所思记录下来,以后我会慢慢更博,争取把以前和以后的学习生活记录下来! 昨天正式”刷”了第一道leetcode,以前...

LeetCode 338. Counting Bits

LeetCode 338. Counting Bits 分析与解答

Leetcode-338. Counting Bits

我的解法: 这道题是看了hinks然后才做出来的,而且还很慢,还是要多练习。 1.题意要素: (1)正整数 (2)时间复杂度O(n), 空间复杂度O(n), 不使用C++ ...

<LeetCode OJ> 338. Counting Bits

Total Accepted: 7119 Total Submissions: 12947 Difficulty: Medium Given a non negative integer n...

leetcode_middle_1_338. Counting Bits

题意: 给定一个非负整数n。从0到这个非负整数(共n+1个数),用一个数组返回这n+1个数的二进制表示的1的个数。 比如 3的二进制表示是11那么1的个数就是2. 分析: 列几个来看下: 0 、   ...
  • pusude
  • pusude
  • 2017年01月24日 20:15
  • 118

【LeetCode】338. Counting Bits

问题描述问题链接:https://leetcode.com/problems/counting-bits/#/descriptionGiven a non negative integer numbe...
  • mrbcy
  • mrbcy
  • 2017年03月15日 21:27
  • 501

Leetcode: 338.Counting Bits

Leetcode: 338.Counting Bits
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode 338 Counting Bits (递推)
举报原因:
原因补充:

(最多只允许输入30个字)