Plus One Leetcode

本文介绍了在给定一个非负整数的数组表示形式下,如何通过两种不同的算法实现对该整数加一的操作。第一种方法使用了较为通用的进位加法逻辑,而第二种方法则利用了题目特点,即只有遇到9时才会有进位,从而实现了更为简洁高效的解决方案。

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

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

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

 

这道题我是用了通用解法,忽略了本题的特殊性。其实如果加1的话,只是遇到9会进一位,剩下都不会有影响。

这个是我之前的解法:

public class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null) {
            return null;
        }
        List<Integer> num = new ArrayList<>();
        int carry = 0;
        for (int i = digits.length - 1; i >= 0; i--) {
            if (i == digits.length - 1) {
                int sum = (digits[i] + 1) % 10;
                carry = (digits[i] + 1) / 10;
                num.add(sum);
            } else {
                int sum = (digits[i] + carry) % 10;
                carry = (digits[i] + carry) / 10;
                num.add(sum);
            }
        }
        if (carry == 1) {
            num.add(carry);
        }
        int[] res = new int[num.size()];
        for (int i = num.size() - 1, j = 0; i >= 0; i--, j++) {
            res[j] = num.get(i);
        }
        return res;
    }
}

但是其实有更简洁的写法。。。

public class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null) {
            return null;
        }
        int l = digits.length - 1;
        for (int i = l; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i] = digits[i] + 1;
                return digits;
            }
            digits[i] = 0;
        }
        int[] newNum = new int[digits.length + 1];
        newNum[0] = 1;
        return newNum;
    }
}

这个解法很巧妙,更巧妙的是如果跳出loop还没有结束,那么只需要重新建个数组把第一位改成1就可以了。

转载于:https://www.cnblogs.com/aprilyang/p/6288495.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值