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:

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

Example 2:

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

Related Topics:Array

## 解題邏輯與實作

### 想法1

 1234567891011121314 class Solution: def plusOne(self, digits): carry = 1 digit_len = len(digits) for i in range(digit_len-1,0-1,-1) : if carry == 0: break carry += digits[i] digits[i] = carry % 10 carry //= 10 return digits if carry == 0 else [carry] + digits 

### 想法2

 1234567891011 class Solution: def plusOne(self, digits): digit_len = len(digits) for i in range(digit_len-1,0-1,-1) : if digits[i] == 9: digits[i] = 0 else: digits[i] += 1 break return [1] + digits if digits[0] == 0 else digits 

 12345678910 class Solution: def plusOne(self, digits): digit_len = len(digits) index = -1 for i in range(digit_len-1,0-1,-1) : if digits[i] != 9: index = i break return [1] + [0] * digit_len if index == -1 else digits[:index] + [digits[index]+1] + [0] * (digit_len-index-1)