Description
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. 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:
1Input: digits = [1,2,3]
2Output: [1,2,4]
3Explanation: The array represents the integer 123.
4Incrementing by one gives 123 + 1 = 124.
5Thus, the result should be [1,2,4].
Example 2:
1Input: digits = [4,3,2,1]
2Output: [4,3,2,2]
3Explanation: The array represents the integer 4321.
4Incrementing by one gives 4321 + 1 = 4322.
5Thus, the result should be [4,3,2,2].
Example 3:
1Input: digits = [9]
2Output: [1,0]
3Explanation: The array represents the integer 9.
4Incrementing by one gives 9 + 1 = 10.
5Thus, the result should be [1,0].
Constraints:
1 <= digits.length <= 1000 <= digits[i] <= 9digitsdoes not contain any leading0’s.
Solution
In this case, we can start iteration from the end. If the last digit is not 9, that means we simply have to add 1 to it and return the current array. If this digit is 9, then we have to check for a digit which is not 9 to the left and increment that by 1 and make every 9 on the right to 0.
If array contains only 9s, then we have to have an array with one more size and the left most number as 1 with every other number as 0 (default value for array).
1class Solution {
2 public int[] plusOne(int[] digits) {
3 for (int i = digits.length - 1; i >= 0; i--) {
4 if (digits[i] < 9) {
5 digits[i]++;
6 return digits;
7 } else {
8 digits[i] = 0;
9 }
10 }
11 // If we didn't return until this, that means we need a new array of one more size
12 int[] result = new int[digits.length + 1];
13 result[0] = 1;
14 return result;
15 }
16}


Comments