leetcode 66. Plus One

博客围绕用数组表示数字并输出该数字加1后的结果展开。介绍了按从右至左做加法并处理进位的思路,还指出在最左边有进位时需分配新数组,同时强调不能直接更新数组元素,要用sum变量保存相加和,避免计算出错。

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

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

用一个数组代表一个数字,让用数组输出这个数字+1后的结果

思路:
按正常的从右至左做加法,同时加上进位
需要注意的是在最左边有进位的时候因为原有的数组长度不够,需要分配一个新的数组

**注意不能用digits[i] = (digits[i] + plus) % 10,然后再plus = (digits[i] + plus) /10
因为前面的操作下digits[i]已经更新,后面再用更新后的digits[i]就会出错,所以用sum变量来保存相加的和

//0ms
    public int[] plusOne(int[] digits) {
        int plus = 0;
        int len = digits.length;
        int sum = 0;
        
        sum = digits[len - 1] + 1 + plus;
        digits[len - 1] = sum % 10;
        plus = sum / 10;
        
        for (int i = len - 2; i >= 0; i--) {
            sum = digits[i] + plus;
            digits[i] = sum % 10;
            plus = sum / 10;
        }
        
        if (plus > 0) {
            int[] result = new int[len + 1];
            for (int i = len - 1; i >= 0; i--) {
                result[i + 1] = digits[i];
            }
            result[0] = plus;
            return result;
        }
        
        return digits;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值