[LeetCode 66] Plus One (easy)

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.

Solution

  1. 從最后一位開始加,可以認(rèn)為+ 1 == 從一開始的進(jìn)位carry = 1.
  2. 先得到加上carry 以后的值,carry重置為0; 如果結(jié)果 >= 10, 那么當(dāng)前位結(jié)果為0, carry == 1;否則當(dāng)前位結(jié)果 == digit[index] + carry
  3. 如果全部掃描完了,carry還是為1,那么說明input是 99, 999這種情況。那么直接生成一個(gè)新的array,長(zhǎng)度為digits.length + 1, 再把首位設(shè)為1,返回這個(gè)新的array即可。
  4. 否則返回digits
class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0)
            return digits;
        
        // handle case less than like 999, 99 which after + 1 the result wont has more digits
        int carry = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            int temp = digits[i] + carry;
            carry = 0;
            
            if (temp >= 10) {
                digits[i] = 0;
                carry = 1;
            } else {
                digits [i] = temp;
            }
        }
        
        // handle special case 999, 99, after + 1, it will have 1 more digit
        if (carry == 1) {
            int[] newDigits = new int[digits.length + 1];
            newDigits[0] = 1;
            
            return newDigits;
        }
        
        return digits;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容