One more solution in Java


  • 0
    R
    public class Solution {
        public int[] countBits(int num) {
            if(num==0)
                return new int[]{0};
            if(num==1)
                return new int[]{0,1};
            int[] dp = new int[num+1];
            dp[0] = 0;
            dp[1] = 1;
            int index = 0;
            for(int i = 2; i <=num; i++) {
                if(isPowerOfTwo(i)){
                    index = 0;
                }
                dp[i] = 1+dp[index++];
            }
            return dp;
        }
        public boolean isPowerOfTwo(int n) {
            if(n < 1) return false;
            return (0 == ((n - 1) & n));
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.