[C语言] leetcode 66. Plus One

来源:互联网 发布:淘宝店铺设置流程 编辑:程序博客网 时间:2024/06/05 02:29

题目:

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.

题目解释:

先解释一下题目意思:给定一个非负整数,然后用一个数组保存这个数字,例如数字100,则数组为[1,0,0];

然后给定数字加1之后再用一个数组保存,并返回这个数组。

答案代码:

/** * 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* returnarray=(int*)malloc(digitsSize*sizeof(int));    int flag=1;    //由于给定数字需要加1,所以flag初始化值设为1    for(int i=digitsSize-1;i>=0;i--)    {            returnarray[i]=(digits[i]+flag)%10;      //数字最低位时加1(flag=1),其他情况根据前一位进位决定            flag=(digits[i]+flag)/10;    }    if(flag==0)    {        *returnSize=digitsSize;    }    else    {        *returnSize=digitsSize+1;        (int*)realloc(returnarray,(digitsSize+1)*sizeof(int));        for(int i=digitsSize;i>0;i--)        {            returnarray[i]=returnarray[i-1];        }        returnarray[0]=1;    }    return returnarray;}


0 0
原创粉丝点击