跳转至

66. Plus One

Leetcode Array Math

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.

分析

这道题目考查的是基本的数组操作和基本的数学加法。一般情况下,只要将数组最后元素加1即可。但是可能会出现进位的情况,所以需要注意进位的加法。特别需要注意的是当最高位进位时的情况。

public int[] plusOne(int[] digits) {

    int carry = 1;
    for (int i = digits.length - 1; i >= 0; i--) {
        int newdigit = carry + digits[i];
        if (newdigit < 10)  {
            digits[i] = newdigit;
            return digits;
        } else {
            digits[i] = newdigit - 10;
            carry = 1;
        }
    }
    int[] digitsLarge = new int[digits.length + 1];
    digitsLarge[0] = 1;
    for (int i = 0; i < digits.length; i++)
        digitsLarge[i+1] = digits[i];
    return digitsLarge;
}