Leetcode 66. Plus One

题目

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given a non-negative integer represented as a non-empty a...
    ShutLove阅读 252评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 今天我独自一个人坐在窗旁 看着外面雨 滴滴答答 我的内心几乎崩溃 我的神经将近爆炸 不知道此刻内心深处到底是什么样...
    小太阳high阅读 201评论 0 1
  • 我要飞到九寨沟去 我要飞到九寨沟去 最初的意图是为了逃亡 逃离都市银灰色的沉重 逃离那份雾蒙蒙的心情 我要飞到九寨...
    欧阳小川阅读 695评论 37 38
  • All your efforts will eventually pay off. @Lynn Lu慧空alway...
    LynnLu慧空6阅读 341评论 0 0