/*
【題目大意】
高精度乘法
【解題思路】
直接把1129製造出來的大數加法用過來:
1、多位數乘一位數,可以直接使用加法完成。
2、多位數乘形如d*10n的數,可以轉換成多位數乘一位數來處理。
3、多位數乘多位數,可以轉換爲若干個“多位數乘形如d*10n的數與多位數乘一位數”之和。
因此,多位數乘多位數最終可以全部用加法來實現,專門另外寫乘法什麼的···何必如此想不開呢···
*/
/*
Run Time: 0secs
Run Memory: 312KB
*/
#include <iostream>
#include <string>
using namespace std;
string numA, numB;
//字符串逆序
inline string changeBack(const string& num){
char buf[num.length()+1];
for(int i=0; i<num.length(); i++)
buf[i] = num[num.length()-i-1];
buf[num.length()] = '\0';
return buf;
}
//大數加法(反序)
inline string Add(string a, string b){
//調節爲a長b短
if(a.length() < b.length()){
string buf = a;
a = b;
b = buf;
}
//補零
a += '0';
while(a.length()-b.length() != 0)
b += '0';
int add = 0;
string result = "";
for(int i=0; i<b.length(); i++){
int buf = add + (a[i]-'0') + (b[i]-'0');
if(buf/10 == 1)
add = 1;
else
add = 0;
result += (buf%10) + '0';
}
if(result[result.length()-1] == '0')
return result.substr(0, result.length()-1);
else
return result;
}
//乘法由加法組成
string Mult(string a, string b){
a = changeBack(a);
b = changeBack(b);
//調節成a長b短
if(a.length() < b.length()){
string buf = a;
a = b;
b = buf;
}
//一位數乘以多位數,其實就是多位數加num次
string temp[b.length()]; //存放中間值
for(int i=0; i<b.length(); i++){
int num = b[i] - '0';
string buf = "0";
for(int j=0; j<num; j++)
buf = Add(a, buf);
temp[i] = buf;
}
//將不同位數加起來
string result = "0";
for(int i=0; i<b.length(); i++){
string buf = temp[i];
for(int j=0; j<i; j++)
buf = '0' + buf;
result = Add(buf, result);
}
return changeBack(result);
}
int main()
{
int T;
cin >> T;
while (T-->0){
cin >> numA >> numB;
cout << Mult(numA, numB) << endl;
}
return 0;
}
Sicily 1381. a*b
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.