Plus One
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.
给定一个数字数组组成的非负整数,给该数加 1.整数的高位存储在表头位置。
分析:
注意进位和最高位是否有进位,如果最高位有进位,则需要重新分配一个新节点存储,数字长度也要加 1。
int* plusOne(int* digits, int digitsSize, int* returnSize) {
int sum = 0;
int index = 0;
int carry = 0;
int *newdigits = NULL;
if(!digits || digitsSize == 0)/*空指针或空数组*/
{
*returnSize = 0;
return digits;
}
*returnSize = digitsSize;
index = digitsSize - 1;
while(index >= 0)
{
sum = (index == digitsSize-1)?(digits[index] + 1 + carry):(digits[index] + carry);
digits[index] = sum % 10;
carry = sum / 10;
if(carry == 0)
{
return digits;
}
--index;
}
if(carry) /*最高位有进位*/
{
*returnSize = digitsSize + 1;
newdigits = (int *)malloc((digitsSize + 1)*sizeof(int));
newdigits[0] = carry;
for(index = 0; index < digitsSize; ++index)
{
newdigits[index+1] = digits[index];
}
return newdigits;
}
return digits;
}
本文介绍了一个针对非负整数数组的加一算法实现。通过遍历数组从最低位开始逐位进行加一操作,并处理进位情况。若最高位产生进位,则需要额外分配内存并调整数字长度。

630

被折叠的 条评论
为什么被折叠?



