2.1.17 Plus One

Link: https://oj.leetcode.com/problems/plus-one/

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

我的代碼:一次過。可以不用再寫。

Time: O(n), Space: O(1), worst case (all digits = 9): O(n)

public class Solution {
    public int[] plusOne(int[] digits) {
        int n = digits.length;
        int[] result = new int[n];
        if(digits[n-1] != 9){
            digits[n-1] += 1;
            return digits;
        }
        int i = n-1;
        while(i>0 && digits[i] == 9){
            digits[i] = 0;
            i--;
        }
        if(digits[i] != 9){
            digits[i] +=1;
        }
        else{
            result = new int[n+1];
            result[0] = 1;
            return result;
        }
        return digits;
    }
}

以上代碼可以更簡潔:

public class Solution {
    public int[] plusOne(int[] digits) {
        int n = digits.length;
        for(int i = n-1; i>=0; i--){
            if(digits[i] != 9){
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        //all digits = 9
        int[] result = new int[n+1];
        result[0] = 1;
        return result;
    }
}

Note: 我的Google 面試題@2014.2.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章