LintCode 407. 加一

Posted zslhg903

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LintCode 407. 加一相关的知识,希望对你有一定的参考价值。

给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。

该数字按照大小进行排列,最大的数在列表的最前面。

 

样例

给定 [1,2,3] 表示 123, 返回 [1,2,4].

给定 [9,9,9] 表示 999, 返回 [1,0,0,0].

 

解:简易版大整型加法

class Solution {
public:
    /*
     * @param digits: a number represented as an array of digits
     * @return: the result
     */
    vector<int> plusOne(vector<int> &digits) {
        // write your code here
        int x=0;
        int sz=digits.size();
        digits[sz-1]+=1;
        x=digits[sz-1]/10;
        digits[sz-1]%=10;
        if(x>0)//有进位
        {
            for(int i=sz-2;i>=0;i--)
            {
                digits[i]=digits[i]+x;
                x=digits[i]/10;
                digits[i]%=10;
                if(x==0)
                    break;
            }
        }
        
        if(x>0)//最后还有额外的进位
        {
            digits.insert(digits.begin(),1);
        }
        return digits;
    }
};

 

以上是关于LintCode 407. 加一的主要内容,如果未能解决你的问题,请参考以下文章

407 加一

LintCode之加一

LintCode 数组

IOS开发-OC学习-常用功能代码片段整理

需要 TFS PowerTools 代理身份验证 HTTP 代码 407

网络摄像头拉流的方法总结(附python代码)