LeetCode 66. Plus One--数字数组最后一个元素加1,保持进位

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.

public class Main {

    public int[] plusOne(int[] digits) {
        int n = digits.length;
        for (int i = n - 1; i >= 0; i--) {
            if (digits[i] < 9) {//数字小于9时
                digits[i]++;
                return digits;
            }
            digits[i] = 0;//数字等于9时
        }//for

        int[] newNumber = new int[n + 1];// 99 999  在这里处理
        newNumber[0] = 1;
        return newNumber;
    }//plusOne

    public static void main(String[] args) {
        //int[] num = new Main().plusOne(new int[]{9, 9, 9});//1000
        //int[] num = new Main().plusOne(new int[]{1, 9, 9});//200
        int[] num = new Main().plusOne(new int[]{1, 0, 0});//101
    }
}











你可能感兴趣的:(Java,算法,面试)