You are given a large integer represented as an array of digits, where each digits[i] is the i-th digit. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: 123 + 1 = 124
Example 2:
Input: digits = [9,9,9]
Output: [1,0,0,0]
Explanation: 999 + 1 = 1000
Start from rightmost digit, add 1, handle carry.
Algorithm:
1class Solution {
2 public int[] plusOne(int[] digits) {
3 int n = digits.length;
4
5 for (int i = n - 1; i >= 0; i--) {
6 if (digits[i] < 9) {
7 digits[i]++;
8 return digits;
9 }
10 digits[i] = 0;
11 }
12
13 // All digits were 9
14 int[] result = new int[n + 1];
15 result[0] = 1;
16 return result;
17 }
18}