LeetCode 66: Plus One
Given a non-empty array of digits representing a non-negative integer, increment the integer by one. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself.
Example:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Q: Can the input array be empty? A: No, the problem states that the array is non-empty.
Q: Should I consider edge cases like [9, 9, 9]
?
A: Yes, your solution should handle cases where there’s a carry-over that impacts the most significant digit.
Q: Can the digits array contain negative values or values greater than 9? A: No, each element in the array represents a single digit from 0 to 9.
1
at the beginning of the array.public 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;
}
// If control comes here means digits were all 9's
int[] result = new int[n + 1];
result[0] = 1; // the most significant digit is 1
return result;
}
}
This solution effectively handles the primary edge cases, including carry-over logic when all digits are 9.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?