Tc的专栏

待重头,收拾旧山河,朝天阙

LeetCode 338 Counting Bits (递推)

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


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/52370372
文章标签: leetcode dp
个人分类: Leetcode Medium
所属专栏: LeetCode
上一篇LeetCode 318 Maximum Product of Word Lengths (位压缩)
下一篇LeetCode 223 Rectangle Area
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭