【数组处理】66

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) {
        for(int i = digits.length-1;i>=0;i--){//对一个数字加1操作,包括进位,使用for循环
            if(digits[i]<9){
               digits[i]++;
               return digits;
            }else digits[i]=0;
        }
        
        //如果for循环没有return,执行到了这里,说明每一位都大于9,则需要数组长度需要变化,并且第一位是1,其余位都是0,new1个数组默认填充0
        int[] newDigits = new int[digits.length+1];
        newDigits[0] = 1;
        return newDigits;
        
    }
}
原文地址:https://www.cnblogs.com/lucky-star-star/p/5053442.html