LeetCode | 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.

//思想类似于前两天的add binary与add two numbers
//数组中,高位在左,低位在右,故反向遍历并维护进位
public class Solution {
    public int[] plusOne(int[] digits) {
        
        if(digits==null || digits.length==0){
            return null;
        }
        
        int carry = 1;     //在第一次循环时,充当one的角色,以后作为进位标志位
        int index = digits.length - 1;
        
        while(index >= 0){
            int temp = digits[index] + carry; 
            int newDigit = temp % 10;
            carry = temp / 10;
            
            digits[index] = newDigit;
            index--;
        }
        
        if(carry > 0){       //因仅仅加1,若此时还有进位,则原数组毕为9999..形式
            int[] result = new int[digits.length+1];
            result[0] = 1;   //新建个扩充数组,且首位为1即可
            return result;
        }else{
            return digits;
        }
        
    }
}



原文地址:https://www.cnblogs.com/dosmile/p/6444439.html