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.
Input: digits =[1,2,3]Output: [1,2,4]Explanation: The array represents the integer 123.Incrementing by one gives 123+1=124.Thus, the result should be [1,2,4].
Example 2:
1
2
3
4
5
Input: digits =[4,3,2,1]Output: [4,3,2,2]Explanation: The array represents the integer 4321.Incrementing by one gives 4321+1=4322.Thus, the result should be [4,3,2,2].
Example 3:
1
2
3
4
5
Input: digits =[9]Output: [1,0]Explanation: The array represents the integer 9.Incrementing by one gives 9+1=10.Thus, the result should be [1,0].
Traverse the Array: Iterate from the last digit to the first.
Addition and Carry Handling:
If the current digit is less than 9, increment it and terminate the function by returning the array.
If the current digit is 9, set it to 0 and move to the next digit.
Handling Full Carry: If all digits are 0 after the loop, it means the number was composed entirely of 9’s. Create an array of length n + 1 with the first element as 1.
publicclassSolution {
publicint[]plusOne(int[] digits) {
int n = digits.length;
for (int i = n - 1; i >= 0; i--) {
if (digits[i]< 9) {
digits[i]++;
return digits;
}
digits[i]= 0;
}
int[] ans =newint[n + 1];
ans[0]= 1;
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defplusOne(self, digits: List[int]) -> List[int]:
n = len(digits)
for i in range(n -1, -1, -1):
if digits[i] <9:
digits[i] +=1return digits
digits[i] =0 ans = [0] * (n +1)
ans[0] =1return ans