1. 程式人生 > >Leetcode 66. Plus One-陣列表示的數值+1,返回新的陣列

Leetcode 66. Plus One-陣列表示的數值+1,返回新的陣列

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

方法:

/**
 * <p>Title: </p>
 * <p>Description: </p>
 *
 * @Author
 * @CreateTime 2019/1/12 11:16
 */
public class Leetcode_66_PlusOne {

    public static void main(String[] args) {
        Leetcode_66_PlusOne leetcode_66_plusOne = new Leetcode_66_PlusOne();
//        int[] arr = new int[]{1, 2, 3, 4};//輸出 1235
//        int[] arr = new int[]{1, 2, 9, 9}; //輸出 1300
//        int[] arr = new int[]{9, 9, 9, 9}; //輸出 10000
        int[] arr = new int[]{8, 9, 9, 9}; //輸出 9000
        System.out.println(leetcode_66_plusOne.plusOne(arr));
    }

    /**
     * +1
     * 0 ms, faster than 100.00%
     *
     * @param digits
     * @return
     */
    public int[] plusOne(int[] digits) {
        int inc;
        int length = digits.length;
        if (digits[length - 1] + 1 < 10) {
            digits[length - 1] = digits[length - 1] + 1;//最右邊先加1,此時小於10,不進位
            return digits;
        }
        inc = 1;//最右邊先加1,此時等於10,進位1
        digits[length - 1] = 0;
        for (int i = digits.length - 2; i >= 0; i--) {//從倒數第二位開始遍歷
            if (inc == 1) {//如果進位是1,則需要一直往前遍歷和計算
                if (digits[i] + inc == 10) {
                    digits[i] = 0;
                    inc = 1;
                } else {
                    digits[i] = digits[i] + inc;
                    inc = 0;
                }
            } else {//當還沒計算到最高位時,如果進位不是1,說明不再有進位,不需要遍歷和計算,直接返回即可
                return digits;
            }
        }

        if (inc == 0) {//計算到最高位時進位是0,則最高位不必加1,直接返回即可
            return digits;
        } else {
            int[] result = new int[length + 1];//說明計算到最高位時,還是有進位,則需要使用新陣列,首位是1,其他位都是0
            result[0] = 1;
//            for (int i = 0; i < length; i++) {
//                result[i + 1] = digits[i];
//            }
            return result;
        }
    }
}

end