LeetCode

[LeetCode] 66. 加一

2018-04-09  本文已影响0人  拉面小鱼丸

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

可以假设整数不包含任何前导零,除了数字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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读