Plus One

Question:

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.

Solution:

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digits) {
 4     reverse(digits.begin(),digits.end());
 5     int t=digits[0]+1;
 6     int val=t%10;
 7     int up=t/10;
 8     *(digits.begin())=val;
 9     for(auto iter=digits.begin()+1;iter!=digits.end();iter++)
10     {
11         t=*iter+up;
12         val=t%10;
13         up=t/10;
14         *iter=val;
15     }
16     if(up)
17         digits.push_back(up);
18     reverse(digits.begin(),digits.end());
19     return digits;    
20     }
21 };

posted on 2015-07-08 22:32  Riden  阅读(159)  评论(0编辑  收藏  举报

导航