Статья пока доступна только на английском.
Problem Description
You are given a large integer represented as an integer array digits, where digits[i] is the i-th digit of the integer.
The digits are ordered from most significant to least significant, left to right.
The number has no leading zeros.
Increment the number by one and return the resulting array of digits.
Constraints
- The array contains from 1 to 100 digits
- The array contains only digits from 0 to 9
- The number has no leading zeros
Examples
Input: [1,2,3]
Answer: [1,2,4]
Solution
To solve the problem we implement the good old column addition.
Each digit of the array is one position of the number. First, we add one to the least significant digit (the rightmost one), as the problem requires, and then follow a simple algorithm.
- If the sum is less than 10, write the sum in place of the current digit.
- If the sum is 10 or more, write the remainder of dividing the sum by 10 in place of the current digit and carry one over to the next digit. Repeat the same steps for all subsequent digits.
- If we are processing the most significant digit (the leftmost one) and the sum is 10 or more, we write the remainder of dividing the sum by 10 into the current digit and add one more digit equal to one.
We traverse the input array from right to left, appending the result for each digit to the end of the result array. This gives us a reversed array, so at the end we just need to reverse it.
export const plusOne = (digits: number[]): number[] => {
const res: number[] = [];
let temp = 0;
for (let i = digits.length - 1; i >= 0; i--) {
const digit = digits[i];
temp += digit;
if (i == digits.length - 1) {
temp += 1;
}
if (temp < 10) {
res.push(temp);
temp = 0;
continue;
}
res.push(temp % 10);
temp = 1;
}
if (temp != 0) {
res.push(temp);
}
for (let i = 0, j = res.length - 1; i < j; i++, j--) {
const tmp = res[i];
res[i] = res[j];
res[j] = tmp;
}
return res;
};Complexity Analysis
Time Complexity
O(n), since we iterate over the whole array twice.
Space Complexity
O(n), since we allocate memory for the result array.