您的位置:首页 > 其它

LeetCode 之 Plus One — C 实现

2015-06-11 16:37 465 查看


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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Plus One