LeetCode -- Plus One

Question:

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.

Analysis:

一个非负数字由一个数组表示,然后对这个数字加一。

这个题目主要是需要考虑特殊情况:数字全部都是9;数字中有某几位是9;一般情况。所以把所有情况考虑到就ok。

Answer:

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits == null)
            return null;
        if(digits[digits.length-1] != 9) {
            digits[digits.length-1] ++;
            return digits;
        }
        boolean flag = true;
        for(int i=0; i<digits.length; i++) {
            if(digits[i] != 9) {
                flag = false;
                break;
            }
        }
        if(flag == true) { //所有位数都为9
            int[] res = new int[digits.length + 1];
            res[0] = 1;
            return res;
        }
        else { //最后一位为9
            for(int i=digits.length-1; i>=0; i--) {
                if(digits[i] == 9)
                    digits[i] = 0;
                else {
                    digits[i] ++;
                    return digits;
                }
            }
        }
        return digits;
    }
    
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4807937.html