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

【Plus One】cpp

时间:2015-04-26 17:59:43      阅读:116      评论: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.

代码

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
            int carry = 1;
            for (std::vector<int>::reverse_iterator i = digits.rbegin(); i != digits.rend() && carry>0; ++i)
            {
                const int tmp = *i+carry;
                *i = tmp%10;
                carry = tmp/10;
            }
            if ( carry >0 ) digits.insert(digits.begin(), carry);
            return digits;
    }
};

Tips:

高精度加法。

利用reverse_iterator来反向迭代vector。

【Plus One】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4457973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!