66. Plus One

Total Accepted: 86284
Total Submissions: 264435
Difficulty: Easy

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.

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
    public int[] plusOne(int[] digits) {
        int i = digits.length - 1;
        if (digits[i] < 9)
            digits[i]++;
        else {
            for (; i >= 0 && digits[i] == 9; --i)
                digits[i] = 0;
            if (digits[0] == 0) {
                digits = new int[digits.length + 1];
                digits[0] = 1;
            } else
                digits[i]++;
        }
        return digits;
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。