- Add to Array-Form of Integer
The array-form of an integer num
is an array representing its digits in left to right order.
- For example, for
num = 1321
, the array form is[1,3,2,1]
.
Given num
, the array-form of an integer, and an integer k
, return the array-form of the integer num + k
.
// runtime 95.96% memory 96.89%
var addToArrayForm = function(num, k) {
const kkk = String(k)
let i = num.length - 1
let j = kkk.length - 1
let carry = 0
while (j >= 0 || (i >= 0 && carry > 0)) {
let sum = carry
if (j >= 0) sum += kkk.charCodeAt(j--) - 48
if (i >= 0) {
sum += num[i]
num[i--] = sum % 10
} else {
num.splice(0, 0, sum % 10)
}
carry = Math.floor(sum / 10)
}
if (carry) {
num.splice(0, 0, carry)
}
return num
}