Leetcode 66. Plus One-数组表示的数值+1,返回新的数组

版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/u010002184/article/details/86353374

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

猜你喜欢

转载自blog.csdn.net/u010002184/article/details/86353374