Number of Steps toreduce a number to zero

/**
Runtime: 45 ms, faster than 7.47% of Java online submissions for Number of Steps to Reduce a Number to Zero.

Memory Usage: 40.2 MB, less than 100.00% of Java online submissions for Number of Steps to Reduce a Number to Zero.
*/
class Solution {
    
    private static int[] arr = new int[1000001];
    
    static {
        arr[0] = 0;
        arr[1] = 1;
        arr[2] = 2;
        for (int i=3; i<1000001; i++) {
            if ((i % 2) == 0) {
                arr[i] = arr[i / 2] + 1;
                continue;
            }
            arr[i] = arr[i - 1] + 1;
        }
    }
    
    // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
    // 0, 1, 2, 3, 3, 4, 4, 5, 4, 5, 5,  6,  5,  6,  6
    
    public int numberOfSteps (int num) {
        
        return arr[num];
        
    }
}

初始化數組比較慢,看別人的寫法。

int count = 0;
        while(num != 0){
            if(num % 2 == 0){
                num = num / 2;
            } else {
                num = num - 1;
            }
            count++;
        }
        return count;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章