首页 > 其他 > 详细

Plus One

时间:2015-07-12 22:56:24      阅读:270      评论:0      收藏:0      [点我收藏+]

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.

//不要再装逼使用unsigned int,这里使用UINT i,当i==0时进行i--,嘿,溢出了,循环继续

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        
        vector<int> res;
        if(!digits.size()) return res;
        
        bool sign=true;
        int i,j,n=digits.size();
        
        if(digits[n-1]!=9) //最后一位非9
        {
            digits[n-1]+=1;
            return digits;
        }
        
        for(i=n-1;i>=0;i--)
        {
            if(sign)
            {
                if(digits[i]==9)
                {
                    res.push_back(0);
                    if(!i) res.push_back(1); //尽头补一位
                }else
                {
                    sign=false;
                    res.push_back(digits[i]+1);
                    for(j=i-1;j>=0;j--)
                    {
                        res.push_back(digits[j]);
                    }
                }
            }
        }
        
        std::reverse(res.begin(),res.end());
        return res;
    }
};

 

Plus One

原文:http://www.cnblogs.com/jason1990/p/4641633.html

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