66. Plus One【leetcode】

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.

题意:一个整数按位存储于一个int数组中,排列顺序为:最高位在array[0] ,最低位在[n-1],例如:98,存储为:array[0]=9; array[1]=8;
解题思路,从数组的最后一位开始加1,需要考虑进位,如果到[0]位之后仍然有进位存在,需要新开一个长度为(n.length + 1)的数组,拷贝原来的数组

public class Solution {
    public int[] plusOne(int[] digits) {
        int len=digits.length;
        
        int sum=0;
        int carray=1;
        for(int i=len-1;i>=0;i--){
            sum=digits[i]+carray;
            digits[i]=sum%10;
            carray=sum/10;
    
            
        }
        if(carray==0){
            return digits; 
        }
        int [] temp=new int[len+1];
            for(int i=0;i<len;i++){
                temp[i+1]=digits[i];
            }
            temp[0]=1;
        
        return temp;
    }
}
不积跬步无以至千里,千里之堤毁于蚁穴。 你是点滴积累成就你,你的丝丝懒惰毁掉你。 与诸君共勉
原文地址:https://www.cnblogs.com/haoHaoStudyShare/p/7342060.html