[LeetCode] 66. 加一

给定一个非负整数组成的非空数组,给整数加一。

可以假设整数不包含任何前导零,除了数字0本身。

最高位数字存放在列表的首位。

原文

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.

Java

class Solution {
    public int[] plusOne(int[] digits) {
        int temp = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            if (temp == 0) {
                break;
            }
            if (digits[i] == 9) {
                digits[i] = 0;
            } else {
                digits[i] += temp;
                temp = 0;
            }
        }
        if (temp == 1) {
            int[] res = new int[digits.length + 1];
            res[0] = 1;
            for (int i = 0; i < digits.length; i++) {
                res[i + 1] = digits[i];
            }
            return res;
        }
        return digits;
    }
}
[LeetCode] 66. 加一_第1张图片

你可能感兴趣的:([LeetCode] 66. 加一)