66. Plus One¶
Description¶
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Example 2:
Input: [9,9,9]
Output: [1,0,0,0]
Constraints:
1 <= digits.length <= 100
.0 <= digits[i] <= 9
.
Solutions¶
I Math¶
Complexity:
- Time complexity: \(O(n)\).
- Space complexity: \(O(1)\).
func plusOne(digit []int) []int {
length := len(digit)
if length == 0 {
return digit
}
for i := length - 1; i >= 0; i-- {
if digit[i] < 9 {
digit[i] += 1
return digit
}
digit[i] = 0
}
digit = append([]int{1}, digit...)
return digit
}