[LeetCode] 66. 加一

weixin_34019929發表於2018-04-09

給定一個非負整陣列成的非空陣列,給整數加一。

可以假設整數不包含任何前導零,除了數字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;
    }
}
5193518-8f04a31370d1c5d3.png

相關文章