Leetcode - Add to Array-Form of Integer

violet posted @ Apr 07, 2020 08:29:23 AM in 算法 with tags Algorithm Golang array , 196 阅读

For a non-negative integer `X`, the array-form of `X` is an array of its digits in left to right order.  For example, if `X = 1231`, then the array form is `[1,2,3,1]`.

Given the array-form `A` of a non-negative integer `X`, return the array-form of the integer `X+K`.

Example 1:

```Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234
```

```func addToArrayForm(A []int, K int) []int {
carry := 0
for i := len(A)-1; i >= 0; i-- {

k := K % 10
K /= 10
sum := A[i] + carry + k
carry = 0
if sum > 9 {
carry = 1
sum -= 10
}
A[i] = sum
}
if K == 0 {
if carry == 1 {
A = append([]int{1}, A...)
}
return A
}
if carry == 1 {
K++
}

prefix := []int{}
for K > 0 {
prefix = append(prefix, K % 10)
K /= 10
}
for i := 0; i < len(prefix)/2; i++ {
prefix[i], prefix[len(prefix)-i-1] = prefix[len(prefix)-i-1], prefix[i]
}

return append(prefix, A...)
}```

(输入验证码)
or Ctrl+Enter