989. Add to Array-Form of Integer [Easy]

这篇博客分享了一种处理整数转换为数组的高效方法,实现了在处理进位时的优化,通过一次循环完成主要计算,并能直接将结果添加到结果列表中。代码运行时间为2毫秒,内存使用低于平均值,具有很好的性能表现。
/**
 * 要求"return the array-form of the integer",但返回类型是List<Integer>就离谱
 * 自己的代码
 * 有一些自己觉得写的很妙的地方:
 * 1. 不单独处理进位,每次将sum产生的进位在循环的最后加到k里
 * 2. 第一个for循环后不判断k是否变为0再区分行为,直接将k中的位加入resList,如果k已经为0,自动不会进入循环(且过程中每取一位要将其插在resList的头部,而非接在后面)
 * Runtime: 2 ms, faster than 99.81%
 * Memory Usage: 41.1 MB, less than 37.38% 
 */
class Solution {
    
    public List<Integer> addToArrayForm(int[] num, int k) {
        List<Integer> res = new LinkedList();
        // calculate all digits in num
        for (int i = num.length - 1; i >= 0 && k > 0; i--) {
            int sum = num[i] + k % 10;
            num[i] = sum % 10;
            k = k / 10 + sum / 10; // add carry bits to k
        }
        // add remained k to resList until k become 0 (k is possible to be 0 when existing the first for-loop)
        for ( ; k != 0; k /= 10) {
            res.add(0, k % 10);
        }
        // add every digit in the calculated num array to resList
        for (int i : num) {
            res.add(i);
        }
        return res;
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值