题目描述
给定任意两个高精度正整数a、b,计算a与b的乘积。
输入
输入文件中有若干行,每一行上有两个用字符串表示的正整数a,b。
输入直到文件结束。
输出
对每个输入行上的两个正整数a,b,在一行上先输出形式a*b=,接着输出a与b的积。
样例输入
12345 6788466
345 66
样例输出
12345*6788466=83803612770
345*66=22770
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string str1, str2, str3;
int a[1000], b[1000], sum[1000], s, temp;
int len1, len2, len3, flag;
while (cin >> str1 >> str2) {
flag = 0;
len1 = str1.length();
len2 = str2.length();
if (len1 < len2) {
str3 = str1;
str1 = str2;
str2 = str3;
flag = 1;
}
len1 = str1.length();
len2 = str2.length();
len3 = len1 + len2;
for (int i = 0; i < len1; ++i) {
a[len1-1-i] = str1[i] - '0';
}
for (int i = 0; i < len2; ++i) {
b[len2-1-i] = str2[i] - '0';
}
if (flag) {
for (int i = len2-1; i >= 0; --i) {
cout << b[i];
}
cout << "*";
for (int i = len1-1; i >= 0; --i) {
cout << a[i];
}
cout << "=";
} else {
for (int i = len1-1; i >= 0; --i) {
cout << a[i];
}
cout << "*";
for (int i = len2-1; i >= 0; --i) {
cout << b[i];
}
cout << "=";
}
memset(sum, 0, sizeof(sum));
temp = 0;
for (int i = 0; i < len3; ++i) {
s = temp;
if (i != len3-1) {
for (int j = min(i, len1 - 1), k = i - j; j >= 0 && j < len1 && k < len2; --j, ++k) {
s += a[j] * b[k];
// cout << j << ", " << k << ", " << s << endl;
}
sum[i] = s % 10;
temp = s / 10;
// cout << temp << endl;
}
else {
sum[i] = (s) % 10;
temp = (s) / 10;
}
}
if (sum[len3-1] != 0)
cout << sum[len3-1];
for (int i = len3-2; i >= 0; --i) {
cout << sum[i];
}
cout << endl;
}
return 0;
}
自认为写得并不好,一个简单的逻辑写得却很复杂,基本功不行啊!!!题目挺简单,我是转换成数组存储然后一位一位的求。