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
.
/**
* @param {number[]} A
* @param {number} K
* @return {number[]}
*/
var addToArrayForm = function(A, K) {
let len = A.length
if(len <= 5) {
let res = 0
for(let i = 0; i < len; i ++) {
res += A[i] * Math.pow(10, len - 1 - i)
}
res += K
let ans = [0]
let i = 0
while(res) {
ans[i ++] = res % 10
res = parseInt(res / 10)
}
console.log(ans)
return ans.reverse()
}else {
let res = 0
for(let i = len - 5, j = 0; i < len; i ++, j ++) {
res += A[i] * Math.pow(10, 4 - j)
}
res += K
let i = 0
let ans = [0]
while(res) {
ans[i ++] = res % 10
res = parseInt(res / 10)
}
if(ans.length <= 5) {
for(let i = 0; i < 5 - ans.length; i ++) {
ans.push(0)
}
for(let i = len - 6, j = 0; i >= 0; i --, j ++) {
ans[5 + j] = A[i]
}
}else {
let yu = ans[5]
let j = 0
for(let i = len - 6; i >= 0; i --, j ++) {
ans[5 + j] = (A[i] + yu) % 10
yu = parseInt((A[i] + yu) / 10)
}
if(yu) ans.push(yu)
}
return ans.reverse()
}
};
具体的解析就不写了,我相信每个人很轻易的都会想到做法的,只是简单和复杂的区别
主要是要注意进位的情况
Result:
Success
Runtime: 148 ms, faster than 100.00% of JavaScript online submissions for Add to Array-Form of Integer.
Memory Usage: 22.8 MB, less than 100.00% of JavaScript online submissions for Add to Array-Form of Integer.