Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
Example:
1.input [ 1, 1 ], return [ 1, 2 ]
2.input [ 9, 9 ], return [ 1, 0, 0]
Already Pass Solution
public int[] PlusOne(int[] digits)
{
/* -- Version One -- */
int num = Int32.Parse(String.Join("", digits)) + 1;
int length = digits.Length;
digits[length - 1]++;
for (int i = length - 1; i > 0; i--)
{
if (digits[i] > 9 && i != 0)
{
digits[i - 1]++;
digits[i] -= 10;
}
}
if (digits[0] > 9)
{
int[] result = new int[length + 1];
result[0] = 1;
for (int i = 0; i < result.Length; i++)
{
result[i] %= 10;
}
return result;
}
else
{
return digits;
}
}
解题思路:
1.使用数组载体计算后判断长度是否有所增加,新建新的数组座位值返回
public int[] PlusOne(int[] digits)
{
/* -- Version Two -- */
Stack<int> result = new Stack<int>();
int index = digits.Length;
digits[index-1]++;
for(int i = index; i > 1; i--)
{
if (digits[i - 1] > 9)
{
digits[i - 2]++;
}
result.Push(digits[i-1]%10);
}
result.Push(digits[0]%10);
if (digits[0] > 9)
{
result.Push(1);
}
return result.ToArray();
}
解题思路:
1.使用栈的数据结构辅助,减少代码量和循环遍历次数
待思考:
1.时间复杂度和空间复杂度降低