关闭

LeetCode 338 Counting Bits (递推)

标签: leetcodedp
331人阅读 评论(0) 收藏 举报
分类:

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;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:569543次
    • 积分:13437
    • 等级:
    • 排名:第954名
    • 原创:800篇
    • 转载:7篇
    • 译文:0篇
    • 评论:119条
    博客专栏