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

大数加法模板

时间:2017-08-15 19:55:52      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:iostream   for   加法   namespace   algo   eve   amp   大数   ret   

计算 a + b

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 string sol;
 6 
 7 void solve(string a, string b){
 8     int j = b.size() - 1, i = a.size() - 1, cnt = 0;
 9     for(; i >= 0 && j >= 0; i--, j--){
10         int x = a[i] - 0;
11         int y = b[j] - 0;
12         sol += (char)((x + y + cnt) % 10 + 0);
13         cnt = (x + y + cnt) / 10;
14     }
15     while(i >= 0){
16         int x = a[i--] - 0;
17         sol += (char)((x + cnt) % 10 + 0);
18         cnt = (x + cnt) / 10;
19     }
20     while(j >= 0){
21         int y = b[j--] - 0;
22         sol += (char)((y + cnt) % 10 + 0);
23         cnt = (y + cnt) / 10;
24     }
25     if(cnt) sol += 1;
26     reverse(sol.begin(), sol.end());
27 }
28 
29 int main(void){
30     string a, b;
31     cin >> a >> b;
32     solve(a, b);
33     cout << sol << endl;
34     return 0;
35 }

 

大数加法模板

标签:iostream   for   加法   namespace   algo   eve   amp   大数   ret   

原文地址:http://www.cnblogs.com/geloutingyu/p/7366838.html

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