989.add-to-array-form-of-integer


Description

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.

Example

Input: num = [1,2,0,0], k = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234

Solution

/**
 * @param {number[]} num
 * @param {number} k
 * @return {number[]}
 */
var addToArrayForm = function(num, k) {
    let result = []
    for(let i = num.length - 1; i >= 0; i--) {
        result.push((num[i] + k) % 10);
        k = parseInt((num[i] + k) / 10);
    }
    while(k) {
        result.push(k % 10);
        k = parseInt(k / 10);
    }
    return result.reverse()
};

文章作者: 阿汪同学
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 阿汪同学 !
评论
  目录