Loading

C++大数加法

 1 #include <iostream>
 2 #include<deque>
 3 #include<string>
 4 
 5 using namespace std;
 6 
 7 string add(string a, string b)   //此函数默认a的长度大于b(可以在main函数里用if语句控制a的长度大于b)
 8 {
 9     deque<int>sum;        //sum用来存储和的每一位
10     int carry = 0;        //carry表示进位
11     int i = a.length()-1;
12     int j = b.length()-1;
13     for(; i >= 0,j >= 0; --i,--j)
14     {
15         int wei_sum = (a[i] - '0') + (b[j] - '0') + carry;   //wei_sum表示a,b每个对应相同的位相加的和
16         if(wei_sum >= 10)
17         {
18             carry = 1;
19             sum.push_front(wei_sum-10);
20         }
21         else
22         {
23             carry = 0;
24             sum.push_front(wei_sum);
25         }
26 
27     }
28     for(int k = a.length()-b.length()-1; k >= 0; --k)        //算a比b长的那部分的和
29     {
30         int wei_sum = (a[k] - '0') + carry;            //此处一定要加上之前的进位值!因为之前的carry有可能为1.
31         if(wei_sum >= 10)
32         {
33             carry = 1;
34             sum.push_front(wei_sum-10);
35         }
36         else
37         {
38             carry = 0;
39             sum.push_front(wei_sum);
40         }
41     }
42     if(carry == 1)
43         sum.push_front(1);
44 
45     string Sum;
46     for(auto d: sum)
47         Sum = Sum + char(d + '0');  //把sum转化为string
48     return Sum;
49 }
50 
51 
52 
53 int main()
54 {
55     string a,b;
56     cin >> a >> b;
57     if(a.length() > b.length())
58         cout << a << " + " << b << " = " << add(a,b);
59     else
60         cout << a << " + " << b << " = " << add(b,a);
61 
62     return 0;
63 }

 

posted @ 2018-07-06 10:01  拾月凄辰  阅读(256)  评论(0编辑  收藏  举报