Subject: 66. Plus one
Given a non-negative integer represented by a non-empty array of integers, add one to the number.
The highest digit is stored in the first position of the array, and each element in the array only stores a single number.
You can assume that in addition to the integer 0, this integer does not start with a zero.
answer:
int* plusOne(int* digits, int digitsSize, int* returnSize)
{
int i=digitsSize-1;
for(i;i>=0;i--)
{
// 如果当前位为1-8,直接+1即可返回
if(digits[i]<9)
{
digits[i]++;
*returnSize=digitsSize;
return digits;
}
// 如果当前位为9,+1=10,所以当前位为0
// 隐式进行+1操作
else
digits[i]=0;
}
// 程序走到这里,最高位产生进位,数组长度需要+1
int* res=(int*)malloc(sizeof(int)*(digitsSize+1));
// 最高位为1
res[0] = 1;
// 拷贝后面的数字到新的数组
for(i=0;i<digitsSize;i++)
{
res[i+1]=digits[i];
}
*returnSize=digitsSize+1;
return res;
}