方法一:动态规划 分奇数和偶数的情况
class Solution { public int[] countBits(int num) { int[] dp = new int[num+1]; for(int i = 0; i <= num; i++) { if(i % 2 == 0) dp[i] = dp[i/2]; else dp[i] = dp[i-1] + 1; } return dp; } }
方法二:i&(i-1)去掉i的最后一位1,所以i&(i-1) < i 则 i&(i-1) 之前算出, 所以len[i] = len[i&(i-1)] + 1
class Solution { public int[] countBits(int num) { int[] dp = new int[num+1]; for(int i = 1; i <= num; i++) { dp[i] = dp[i&(i-1)] + 1; } return dp; } }