[leet code] Plus One

本文详细解析了如何实现数组形式的大数加一操作,通过三种典型情况讨论:直接加一、部分九进位及全九进位的情况,并提供了一种类似手动计算的方法,通过临时数组保存结果。

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

==============

Analysis: 

There are 3 cases of this problem:

1. just add one at the lowest digit, e.g. 123 + 1 = 124. 

2. some digits except the hight is 9, e.g. 119 + 1 = 120; 199+1= 200. 

3. all the digits are 9, e.g. 9+1 =10, 99+1=100, 999+1=1000. 

Accordingly, my idea is the same as manual calculation, add one to the lowest digit, using a variable "plus" to keep if the result is 10, then add this "plus" to the next digit.  Continue this process till all the digits in the original array processed.  

In order to cope with the 3 case, I introduced a temporary array, length of which is the length of original array + 1 to keep the result.  Note that once the array created, length of which cannot be changed.  

Finally, I move the result from temporary to the result array (at this time, the result array can be created according the the length of the result).

public class Solution {
    public int[] plusOne(int[] digits) {
        int length = digits.length;
        if(length == 0) return digits;
        

        // add one to original number, and store the result in to new array <- length of new array = length of original array +1
        int plus = 0;
        int[] temp = new int[length+1];
        for(int i=length-1; i>=0; i--){
            int sum = 0;
            if(i == length-1) sum = digits[i]+1;// the 1st time
            else sum = digits[i] + plus;
            
            plus = sum/10;
            temp[length-1-i] = sum%10;
            
            if(i==0 && plus ==1) temp[length] = 1; //the highest digit
        }
        
        
        int newLength = 0;
        if(temp[length] == 1) newLength = length+1;
        else newLength = length;
        
        int[] rs = new int[newLength];
        for (int i=0; i<newLength; i++){
            rs[i] = temp[newLength-i-1];
        }
        
        return rs;
    }
}

Remark: my approach might not look elegant, but I believe it's strait foreword, and the time complexity is not too bad, O(2n).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值