66. Plus One

大数加法优化
Question

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.

思路

实质是用数组实现了大数加法,从最后一位加1开始,设置进位,如到数组头时仍有进位则将数组按位后移,0位补上进位。

代码
public class Solution {
    public int[] plusOne(int[] digits) {
        int[] result = new int[digits.length + 1];
        int c = 1;//进位
        for(int i = digits.length - 1;i >= 0;i--){
            int and = digits[i] + c;
            int low = and%10;
            c = and/10;
            digits[i] = low;
        }
        if(c != 0){
            result[0] = c;
            for(int i = 0;i < digits.length;i++){
                result[i + 1] = digits[i];
            }
            return result;
        }
        else
            return digits;
    }
}
结果及分析

【You are here!
Your runtime beats 5.29% of javasubmissions.】时间复杂度为O(n+1),空间复杂度为O(n+1);

二刷THOUHGT II

其实没必要从头加到尾,只有在都是9的情况下才会发生这种情况。从尾开始遍历,若遍历的元素小于9,则加一返回数组就可以了。若等于9,则将其置为0.如果遍历完还没有返回,说明没有遇到小于9的情况。所以要新建一个数组,并将其开头置为1,不用把原数组中的数字导入,因为他们都是0.

CODE
public class Solution {
    public int[] plusOne(int[] digits) {
        int n =  digits.length;
        for(int i = n - 1;i >= 0;i--){
            if(digits[i] < 9){
                digits[i]++;
                return digits;
            }
            else
                digits[i] = 0;
        }
        int[] arr = new int[n + 1];
        arr[0] = 1;
        return arr;
    }
}
RESULT

time complexity is O(n),space complexity is O(N);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值