Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
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.
Solutions:
For each element in the digits, from back to the top, it follows the law that
if it is smaller than 9, plus one and return;
if it is 9, turn to 0 and plus one to the left element, which will keep going until the element left to the current one isn't equal to 9 occurs.
Note that for the digits composed by n times 9, the answer should be (n+1) length with 1 as the first digit.
Java:
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[] newNumber = new int [n+1];
newNumber[0] = 1;
return newNumber;
}
// https://leetcode.com/problems/plus-one/discuss/24082/My-Simple-Java-Solution
C++:
void plusone(vector<int> &digits)
{
int n = digits.size();
for (int i = n - 1; i >= 0; --i)
{
if (digits[i] == 9)
{
digits[i] = 0;
}
else
{
digits[i]++;
return;
}
}
digits[0] =1;
digits.push_back(0);
}
// https://leetcode.com/problems/plus-one/discuss/24084/Is-it-a-simple-code(C%2B%2B)