问题描述:

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.

代码如下 0ms

/**
 * 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 len = sizeof(int) * (digitsSize + 1);
    int *plus = malloc(len);
    memset((void *)plus,0,len);
    
    int sum   = 0;
    int carry = 1;
    
    for(int i = digitsSize -1;i>=0; --i)
    {
        sum = digits[i] + carry;
        if(sum > 9)
        {
            plus[i+1] = 0;
            carry = 1;
        }
        else
        {
            plus[i+1] = sum;
            carry = 0;
        }
    }
    
    if(carry == 1)
    {
        plus[0] = 1;
    }
    
    if(plus[0] == 0)
    {
        *returnSize = digitsSize;
        plus++;
    }
    else
    {
        *returnSize = digitsSize + 1;
    }
     
    return plus;
  
}

  

posted on 2017-12-05 10:29  gtxvs  阅读(178)  评论(0编辑  收藏  举报