1 question
Given a nonnegative integer represented by a nonempty array of integers, add one to the number. The highest digit is stored at the beginning of the array, and each element in the array stores only a single number. You can assume that other than the integer 0, the integer will not start with zero.
Example 1:
输入:digits = [1,2,3]
输出:[1,2,4]
解释:输入数组表示数字 123。
Example 2:
输入:digits = [4,3,2,1]
输出:[4,3,2,2]
解释:输入数组表示数字 4321。
Example 3:
输入:digits = [0]
输出:[1]
hint:
1 <= digits.length <= 100
0 <= digits[i] <= 9
2 answers
The important and difficult point is whether it is necessary to add a slice. To add a slice, use append. To add a slice in front, add it append([]int{1}, digits...),
at the end of the original slice.s1 = append(s1, 1)
func plusOne(digits []int) []int {
k := 1//判断需不需要增加一位
for i := len(digits) - 1; i >= 0; i-- {
digits[i]++
if digits[i] >= 10 {
// 如果已经循环完毕,则还多出一个1,在后面补齐
digits[i] -= 10
} else {
k = 0
break
}
}
// 如果需要增加一位则重组切片
if k == 1 {
digits = append([]int{
1}, digits...)
}
return digits
}
3Related links
https://blog.csdn.net/snans/article/details/105182524
Source: LeetCode
link: https://leetcode-cn.com/problems/plus-one