[Java][LeetCode][Array] Plus One #66
You are given a large integer represented as an integer array digits
, where each digits[i]
is the ith
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0
's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
第一次用的方式:先將array合成integer,

測試資料出現了超過2⁶⁴的大數字,所以改變方向。
以下是我認為的正解:
將位元逐一推進,判斷最後一個數字+1 (num)之後是否需要進位,如果要進位,就把num-10後存回原本的位置,如果不需要進位,就將num直接存回原本的位置,已次類推到走完digits每個元素。假如在走完全部的digits後,最後一個位元是沒有進位的,那就直接把修改後的digits回出去,如果還有進位,就把開一個新的array出來,array大小為digits+1,把第0個元素設為1,其餘數都跟digits一樣,最後回出這個新的array。

I tried to convert the array to integer. However, the test patent appears a large number, over ²⁶⁴. I change my thinking. If I can’t plus one directly, maybe I need to use the approach: “carry”. The last number of array plus one. When this result is larger than 10, I will save num-10 to the original position, and set carry state to true. else just save the result to the same position. Until traverse all elements of digits. After I did the traversal, if the carry state is false, I return digits directly. Otherwise, I create a new array and its size is digits+1, put digits from the index is 1 to digits length. Return the new array and finish this process.