題目:
The problem is to multiply two integers X, Y . (0 ≤ X, Y < 10250)
Input
The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.
Output
For each input pair of lines the output line should consist one integer the product.
Sample Input
12
12
2
222222222222222222222222
Sample Output
144
444444444444444444444444
其實這道題就是大數(shù)乘法翅敌,不過要注意前導(dǎo)零睦授,另外結(jié)果為0的情況要特判侣诺。
參考代碼:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;//兩位數(shù)和兩位數(shù)相乘最多不超過4位數(shù);
void bigmultiply(string a, string b) {
int lena = a.size();
int lenb = b.size();
int lenr = lena + lenb;
int *a1 = new int[lena];
int *b1 = new int[lenb];
int *result1 = new int[lenr];
for (int i = 0;i < lenr;++i) {//這里要小心亂碼挺举,最好進行初始化;
result1[i] = 0;
}
int x, y, z;//記錄個位十位;//10以內(nèi)的兩個數(shù)相乘結(jié)果均為2位數(shù);
int curr;//記錄當前正在計算的位置, 倒序;
for (int i = 0;i < a.size();++i) a1[i] = a[i] - '0';//將字符轉(zhuǎn)換為數(shù)字;
for (int i = 0;i < b.size();++i) b1[i] = b[i] - '0';
/*
for (int i = 0;i < lena;++i) {
cout << a1[i];
}
cout << endl;
for (int j = 0;j < lenb;++j) {
cout << b1[j];
}
cout << endl;
*/
for (int i = b.size()-1;i >= 0;--i) {
curr = a.size() + i;//實際為lenr - (lenb - i)得到;
for (int j = a.size()-1;j >= 0;--j) {
z = b1[i] * a1[j] + result1[curr];//上一位傳過來的進位;
//cout << "................" << z << endl;
x = z % 10;//提取個位;
y = z / 10;//提取十位;
result1[curr] = x;
curr--;
result1[curr] += y;//相當于進位;
}
}
int pos = 0;
for (int i = 0;i < lenr;++i) {
if (result1[i] != 0) {
pos = i;
break;
}
}
//cout << lenr << " " << pos << endl;
for (int i = pos;i < lenr;++i) {
//cout << result1[i] << endl;
cout << result1[i];
}
cout << endl;
delete[] a1;
delete[] b1;
delete[] result1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
string a, b;
while (cin >> a >> b) {
//cout << a << " " << b << endl;
if (a == "0" || b == "0") cout << "0" << endl;
else bigmultiply(a, b);
}
return 0;
}