首页 > 其他 > 详细

LeetCode-easy-PlusOne

时间:2020-01-08 19:41:45      阅读:91      评论:0      收藏:0      [点我收藏+]

Plus One

问题较为简单,主要是要处理9999这种极端情况加一后的元素变化,在c++中直接可以用vector先对每个元素进行判断,如果是9,就对当前置0,再在最后对首元素置一并且再多加一个元素。

//cpp
class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int length = digits.size();
        for (int i = length - 1; i>=0; i--) {//this judge condition must be i>=0,because we need consider just one element conditions.
            if (digits[i] == 9)
                digits[i] = 0;
            else
            {
                digits[i]++;
                return digits;
            }
        }
        digits[0] = 1;
        digits.push_back(0);
        return digits;
    }
};
int* plusOne(int* digits, int digitsSize, int* returnSize) {
    int carry = 1;//be used forward add
    int i = digitsSize;
    int *ret = (int*)malloc(sizeof(int)*(digitsSize + 1));//allocate heap_memory
    while (i > 0) {
        ret[i] = (digits[i - 1] + carry) % 10;//noted:i is from tail go to head,therefore the head one will be rantom, need judge second number.
        carry = (digits[i - 1] + carry) / 10;
        i--;
    }
    if (!ret[1])
    {
        ret[0] = 1;
        *returnSize = digitsSize + 1;
        return ret;
    }
    else
    {
        *returnSize = digitsSize;
        return ret+1;
    }

}

LeetCode-easy-PlusOne

原文:https://www.cnblogs.com/Yekko/p/12168088.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!