Sicily 1381. a*b【高精度乘法】

来源:互联网 发布:淘宝前端团队 编辑:程序博客网 时间:2024/05/16 03:24

题目链接在此


乘法就是加法,高精度乘法肯定要有高精度加法支撑啦。

不过对于x*y,相比于直接把x的加法循环y次,不如来点快捷的(而且乘数y也很大,循环怎么弄?)!

每次只拿xy的个位数相乘(也就是循环做加法),然后把被乘数x末尾添加“0”(也就是把x乘以10),再把y抹去最后一位。进入下次循环直到y变成空串为之。

本来STL里的string类有很多方便的函数,比如back()取末尾字符,pop_back()删除末尾字符等等,但西西里都不让用。所以只好写得别扭一些了=。=


#include<iostream>#include<string>using namespace std;int charToInt(char a) {  //  字符转成整型的函数return a - '0';}char intToChar(int n) {  //  整型转成字符的函数return n + '0';}string add(string a, string b) {  //  高精度加法if (a.size() > b.size())  //  确保a短b长swap(a, b);while (a.size() < b.size())a = "0" + a;string result(a.size(), '0');int carry = 0;for (int i = a.size() - 1; i >= 0; i--) {result[i] = intToChar((charToInt(a[i]) + charToInt(b[i]) + carry) % 10);carry = (charToInt(a[i]) + charToInt(b[i]) + carry) / 10;}return carry ? ("1" + result) : result;}string multiply(string a, string b) {string product = "0";int LSB;  //  乘数的最右一位if (a.size() > b.size())  //  确保a短b长, a做乘数,b做被乘数.等式是b*aswap(a, b);int alen = a.size();while (true) {LSB = charToInt(a[alen - 1]);alen--;for (int i = 1; i <= LSB; i++)product = add(b, product);if (alen != 0)b += "0";elsebreak;}return product;}int main() {int caseNum;string a, b;cin >> caseNum;while (caseNum--) {cin >> a >> b;cout << multiply(a, b) << endl;}return 0;}



0 0