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.
题目的意思是用一个数组来表示一个非零的数。
Solution:
public class Solution
{
public int[] plusOne(int[] digits)
{
int carry = 0;
for(int i = digits.length - 1; i >= 0; i --)
{
if(i == digits.length - 1)
{
digits[i] = digits[i] + 1;
}
else
{
digits[i] = digits[i] + carry;
}
if(digits[i] > 9)
{
carry = 1;
digits[i] = digits[i] % 10;
}
else
carry = 0;
}
if(carry != 0)
{
int[] result = new int[digits.length + 1];
result[0] = 1;
for(int i = 1; i < result.length; i ++)
{
result[i] = 0;
}
return result;
}
return digits;
}
}