989. Add to Array-Form of Integer

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

Details 

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值