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
原创粉丝点击