[Java] LeetCode - Counting Bits

Counting Bits

class Solution {
    public int[] countBits(int n) {
        if(n==0)
            return new int[]{0};
        if(n==1)
            return new int[]{0,1};
        if(n==2)
            return new int[]{0,1,1};
        
        int[] arr = new int[n+1];
        arr[0] = 0;
        arr[1] = 1;
        arr[2] = 1;
        arr[3] = 2;
        
        int num = 2;
        
        for(int i=4; i<n+1; i++){
            if(num * 2 == i)
                num *= 2;
            
            arr[i] = arr[i-num]+1;
        }
        
        return arr;
    }
}

좋은 웹페이지 즐겨찾기