題目敘述
請設計一個程式,此程式可以不斷地輸入兩個值N、M, N、M最大可以到1000位數,當N或M<=0時則離開程式,請將N、M相加並輸出其結果。
答題思路
略
參考答案
解法一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str1, str2;
while(cin >> str1 >> str2 && str1[0]>='0' && str2[0]>='0') {
bool c = 0;
if(str1.size() < str2.size())
swap(str1, str2);
str2.insert(str2.begin(), str1.size()-str2.size(), '0');
transform(str1.crbegin(), str1.crend(),
str2.crbegin(), str1.rbegin(), [&c](char a, char b) {
int ans = a + b + c - 96;
c = ans > 9;
return ans % 10 + 48;
});
str1.erase(0, str1.find_first_not_of('0'));
if(c) cout << '1';
cout << str1 << endl;
}
return 0;
}
|
解法二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#include <iostream>
using namespace std;
int main() {
string a, b;
while (cin >> a >> b) {
int na[1000] = {0}, nb[1000] = {0}, c=0;
for(int i=0; i<a.size(); i++)
na[i] = a[a.size() - i - 1] - 48;
for(int i=0; i<b.size(); i++)
nb[i] = b[b.size() - i - 1] - 48;
for (int i =0; i<1000; i++) {
int s = na[i] + nb[i] + c;
c = s > 9;
na[i] = s % 10;
}
bool flag = true;
for(int i=1000; i>0; i--) {
if(flag == false or na[i-1] != 0) {
flag = false;
cout << na[i-1];
}
}
cout << endl;
}
}
|