Java solution


  • 0
    L
    public int[] countBits(int num) {
            int[] arr = new int[num+1];
            for(int i=0;i<=num;i++) {
                if(i==0) {
                    arr[0] =0;
                }
                else if(i==1) {
                    arr[1] =1;
                }
                else if(i==3) {
                    arr[3] = 2;
                }
                else if((i&(i-1))==0) {
                    arr[i]=1;
                }
                else {
                   int pow = (int)Math.pow(2,(int)(Math.log(i)/Math.log(2)));
                   arr[i]=arr[pow]+arr[i-pow];
                }
                
            }
            return arr;
        }
    

Log in to reply
 

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