[leedcode 66] Plus One

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.

public class Solution {
    public int[] plusOne(int[] digits) {
        //本题关键点,需要设置一个进位的变量carry
        //carry初始值为1,代表加1,这里很讨巧,如果不这样设,需要把最后一位单独拿出来讨论
        //还有一处需要注意:如果最高位有进位,需要resize数组
        int len=digits.length;
        //if(len<1) return digits;
        int carry=1;
        for(int i=len-1;i>=0;i--){
            
            int temp=digits[i]+carry;
            digits[i]=temp%10;
            carry=temp/10;
            
        }
        if(carry>0){
            int[] newdigits=new int[len+1];
            for(int i=1;i<len+1;i++){
                newdigits[i]=digits[i-1];
            }
            newdigits[0]=carry;
            return newdigits;
        }else return digits;
        
    }
}
原文地址:https://www.cnblogs.com/qiaomu/p/4643562.html