美文网首页
Leetcode 66. Plus One

Leetcode 66. Plus One

作者: persistent100 | 来源:发表于2017-06-27 10:54 被阅读0次

    题目

    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.

    分析

    给出一个整数数组表示一个非负大整数。要求加一后返回。直接依次对各个位加一进行计算,当大于10进位。最后长度需要判断。

    /**
     * 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 *ans=(int *)malloc(sizeof(int)*(digitsSize+1));
        *returnSize=0;
        int temp=1;
        for(int i=digitsSize-1;i>=0;i--)
        {
            temp=temp+digits[i];
            if(temp>9)
            {
                ans[i+1]=temp%10;
                temp=temp/10;
            }
            else
            {
                ans[i+1]=temp;
                temp=0;
            }
        }
        if(temp!=0)
        {
            ans[0]=1;
            *returnSize=digitsSize+1;
        }
        else
        {
            for(int i=0;i<digitsSize;i++)
                ans[i]=ans[i+1];
            *returnSize=digitsSize;
        }
        return ans;
    }
    

    test

    相关文章

      网友评论

          本文标题:Leetcode 66. Plus One

          本文链接:https://www.haomeiwen.com/subject/bcoscxtx.html