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.
代码version 1
int* plusOne(int* digits, int digitsSize, int* returnSize)
{
int sum = 0;
int size = 0;
for(int i = 0;i < digitsSize ;i++)
{
sum = sum *10 + digits[i];
}
sum = sum + 1;
/*计算位数*/
do
{
size++;
sum = sum /10;
}while(sum);
*returnSize = size;
int *result = (int *)malloc(size *sizeof(int));
for(int i = size - 1;i > -1;i--)
{
result[i] = sum % 10;
sum = sum /10;
}
return result;
}
上述代码在结果超过int能表示的最大数后将出错,处理思路应当采用大整数相加。下图是gdb调试中当数组含有10个元素[9,8,7,6,5,4,3,2,1,0]时如下所示,当我们前一步sum值是98765432时还是正确的,再乘以10加上1时出错,超出了整数能表示的最大范围。
代码version2
利用整数加法的原理,从最低位开始相加,如果相加结果大于当前进制(10)则产生进位,直到没有产生进位。如果是999999……9这种形式,加1之后会产生进位,因此申请的size会加一。
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize)
{
int flag = 1;
int temp = 0;
int size = 0;
for(int i = digitsSize - 1;i > -1;i--)
{
/*digits[i]与flag计算相互依赖,需要temp*/
temp = (digits[i] + flag)/10;
digits[i] = (digits[i] + flag ) % 10;
flag = temp;
/*如果此次运算没产生进位,结束循环*/
if(!flag)
break;
}
/*最高位产生进位如999+1,申请空间长度加1*/
size = (flag)?digitsSize + 1:digitsSize;
/*出参带出实际长度*/
*returnSize = size;
int *result = (int *)malloc(size *sizeof(int));
if(flag)
{
/*最高位产生进位,只能为1*/
result[0] = 1;
for(int i = 0; i < digitsSize;i++)
result[i+1] = digits[i];
}
else
{
for(int i = 0; i < digitsSize;i++)
result[i] = digits[i];
}
return result;
}