LeetCode2.1.17 @ Plus One 数组数字加一 D1F2

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.

初始定义carry=1,来用做PlusOne。时间复杂度O(n),空间复杂度O(1)。

如果到了MSB,最坏case是全部为9,那么需要重新建立array,赋值成[1,0,0...],空间复杂度上升为O(n)。

public class Solution {
    public int[] plusOne(int[] digits) {
        int carry=1;//for LSB, carry is the "PlusOne"
        for(int i=digits.length-1;i>=0;i--){//【注意1】
            int temp=digits[i]+carry;
            digits[i]=temp%10;//【注意2】
            carry=temp/10;//【注意3】
            if(carry==0)//【注意4】
                return digits;
        }
        
        int[] res=new int[digits.length+1];
        res[0]=1;
        return res;
    }
}

【注意1】cuz the length may be 1,so avoid using "digits.length-2"。另外注意i--的循环,i>=0别写错,在此出过compile error
【注意2】x%10,取余实质是 x-10-10-10 直到不能再减得到的数。同理x%6
【注意3】使用x/10来表示carry,否则用if判断太复杂
【注意4】之前我的code把 if 放在循环外面,判断MSB是否进位;放在循环里面更节省资源,只要MSB之前没有进位,那么久不用构造新Array。

【后记】follow up问题:http://blog.csdn.net/linhuanmars/article/details/22365957

我觉得为什么Google喜欢的原因是后续可以问一些比较基本的扩展问题,比如可以扩展这个到两个数组相加,或者问一些OO设计,假设现在要设计一个BigInteger类,那么需要什么构造函数,然后用什么数据结构好,用数组和链表各有什么优劣势。这些问题虽然不是很难,但是可以考到一些基本的理解,所以平时准备有机会还是可以多想想哈。


附:第一次写错的code

public class Solution {
    public int[] plusOne(int[] digits) {
        int carry=0;
        for(int i=digits.length-1;i>=0;i--){
            int temp=digits[i]+1+carry;
            if(temp%10==0){
                digits[i]=temp%10;
                carry=1;
            }
            else{
                digits[i]=temp%10;
                carry=0;
            }
        }
        if (carry==1){
            int[] res=new int[digits.length+1];
            res[0]=1;
            return res;
        }
        else{
            return digits;
        }
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值