1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution { public int[] countBits(int num) { int[] dp = new int[num + 1]; dp[0] = 0; if (num == 0) { return dp; } dp[1] = 1; if (num == 1) { return dp; }
for (int i = 2; i <= num; i++){ if (((i-1) & 1) == 1) { String str = Integer.toBinaryString(i - 1); int index = -1; int n = str.length(); for (int j = n-1; j >=0; j--) { if (str.charAt(j) == '0') { index = j; break; } } if (index == -1) { dp[i] = 1; }else { dp[i] = dp[i - 1] - (n-index-1) + 1; } }else { dp[i] = dp[i - 1] + 1; } } return dp; } }
|