[Lintcode]Plus One

本文介绍了一个针对非负整数的加一算法实现,该整数以数字数组形式表示。通过遍历数组并逐位进行进位计算,最终返回加一后的结果。特别地,文章还讨论了处理边界情况的方法,例如当输入为全9数组时如何处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Example

Given [1,2,3] which represents 123, return [1,2,4].

Given [9,9,9] which represents 999, return [1,0,0,0].


加1后结果可能比数组更长,因此不能在算法开始决定新数组长度。另外考虑到参数为int型数组,所以使用arrayList的话,虽然可以解决长度问题,但是又涉及到Integer转int和list转array,所以效率未必更好。 所以这里我们在本地数组上直接操作,如果最后发现要增加数组长度,则从新申请一个新数组。


public class Solution {
    /**
     * @param digits a number represented as an array of digits
     * @return the result
     */
    public int[] plusOne(int[] digits) {
        int nextVal = 1;
        for(int i = digits.length - 1; i >= 0; i--){
            int tmp = (digits[i] + nextVal) / 10;
            digits[i] = (digits[i] + nextVal) % 10;
            nextVal = tmp;
        }
        if(nextVal == 0) return digits;
        else {
            int[] res = new int[digits.length + 1];
            res[0] = nextVal;
            for(int i = 1; i < res.length; i++)
                res[i] = digits[i - 1];
            return res;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值