码迷,mamicode.com
首页 > 其他好文 > 详细

Plus One

时间:2015-07-12 22:58:27      阅读:167      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!