题目
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
解题思路
用一个0-9的数字组成的数组代表一个正整数,将这个正整数加1
个位加1后,需要从个位开始逆序遍历这个数组,更新每一位的值,注意进位
代码
func plusOne(digits []int) []int {
len1 := len(digits)
digits[len1 - 1] = digits[len1 - 1] + 1
var carry int
if digits[len1 - 1] == 10 {
carry = 1
digits[len1 - 1] = 0
}
for i := len1-2; i >= 0; i-- {
digits[i] = carry + digits[i]
if digits[i] == 10 {
digits[i] = 0
carry = 1
} else {
carry = 0
}
}
if carry == 1 {
var ret []int
ret = append([]int{carry}, digits...)
return ret
} else {
return digits
}
}