題目
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
}
}