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

(leetcode)Plus One

时间:2015-08-02 21:19:04      阅读:81      评论: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.

 

大数字加法,一开始以为只是简单地整数加法,后来才发现是大数字

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digit){
 4 //         int len = digit.size();
 5 //         long long res = 0;
 6 //         reverse(digit.begin(),digit.end());
 7 //         for(int j = len-1;j >= 0;--j)
 8 //         {
 9 //             res = res*10+ digit[j];
10 //         }
11 //         long long newres = res+1;
12 //         digit.clear();
13 //         while(newres!=0)
14 //         {
15 //             int a = newres%10;
16 //             digit.push_back(a);
17 //             newres /= 10;
18 //         }
19 //         reverse(digit.begin(),digit.end());
20 //         return digit;
21 
22         int carry = 0;
23         //reverse(digit.begin(),digit.end());
24         vector<int> newvec;
25         int len = digit.size();
26         for(int i=len-1;i>=0;--i)
27         {
28             int tmp;
29             if(i == len-1)
30             {
31                 tmp = digit[i] + 1;
32             }
33             else
34                 tmp = digit[i] + carry;
35             
36             carry = 0;
37             
38             if(tmp>=10)
39             {
40                 carry = 1;
41                 tmp=tmp%10;
42                 newvec.push_back(tmp);
43             } 
44             else
45             {
46                 newvec.push_back(tmp);
47             }
48             
49             if(i == 0 && carry == 1)
50             {
51                 newvec.push_back(carry);
52             }
53         }
54         reverse(newvec.begin(),newvec.end());
55         return newvec;
56     }
57 };


 

(leetcode)Plus One

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4696619.html

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