66. Plus One
Explanation
To increment a large integer represented as an array of digits by one, we start from the least significant digit and move towards the most significant digit. We add 1 to the current digit and check if there is any carry. If there is a carry, we continue the process with the next digit. If there is no carry after incrementing the last digit, we stop and return the updated array of digits.
- Time complexity: O(n) where n is the number of digits.
- Space complexity: O(1)
class Solution {
public int[] 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[] result = new int[n + 1];
result[0] = 1;
return result;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.