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

Plus One

时间:2015-04-18 17:23:35      阅读:97      评论: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.

 

Analyse: To reduce complexity, if the current addition does not make carry, then stop pushing numbers into a stack.

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digits) {
 4         vector<int> result;
 5         vector<int> help;
 6         int carry = 1;
 7         int temp = 0;
 8         
 9         for(int i = digits.size() - 1; i >= 0; i--){
10             temp = digits[i] + carry;
11         
12             if(temp >= 10){
13                 carry = 1; 
14                 temp %= 10;
15             }
16             else{
17                 carry = 0;
18                 digits[i] = temp;
19                 for(int j = i + 1; j < digits.size(); j++){
20                     digits[j] = help.back();
21                     help.pop_back();
22                 }
23                 return digits;
24             }
25             help.push_back(temp);
26         }
27         if(carry == 1) help.push_back(1);
28         while(help.size()){
29             result.push_back(help.back());
30             help.pop_back();
31         }
32         return result;
33     }
34 };

 

Plus One

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4437578.html

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