Bigint Multiplication
時間限制:10000ms
單點時限:1000ms
記憶體限制:256MB 描述
Given 2 nonnegative integers a and b, calculate a × b. 輸入
One line with 2 integers a and b separated by a single space.
0 ≤ a, b ≤ 10100. 輸出
The value of a × b. 範例輸入
100000000000000000000 100000000000000000000 範例輸出
10000000000000000000000000000000000000000 題目解讀
類比豎式乘法,其中一個逐位乘以另一個數,再將結果乘以十的對應次冪累加起來。
思路:
1. 大數加大數,這個很好實現。
2. 大數乘個位元,這個也很好實現。
3. 大數乘大數,可以變成大數分別乘個位元,然後用大數加大數進行匯總。
另外需要注意有0的情況。
#include <iostream>#include <string>#include <algorithm>using namespace std;// char to intinline int c2i(char c){ return c - '0';}// int to charinline char i2c(int i){ return i + '0';}// string(one number) multiply char(one bit of the other number)string sMc(string s, char c) { reverse(s.begin(), s.end()); string r; int carry = 0; for (int i = 0; i < s.length(); ++i) { int n = c2i(s[i]) * c2i(c) + carry; r += i2c(n % 10); carry = n / 10; } if (carry != 0) { r += i2c(carry); } reverse(r.begin(), r.end()); return r;}// string(one number) add string(the other number)string sAs(string s1, string s2) { if (s1.length() < s2.length()) { swap(s1, s2); } s2 = string(s1.length() - s2.length(), '0').append(s2); reverse(s1.begin(), s1.end()); reverse(s2.begin(), s2.end()); string s3; int carry = 0; for (int i = 0; i < s1.length(); ++i) { int n = c2i(s1[i]) + c2i(s2[i]) + carry; s3 += i2c(n % 10); carry = n / 10; } if (carry != 0) { s3 += i2c(carry); } reverse(s3.begin(), s3.end()); return s3;}// string(one number) multiply string(the other number)string sMs(string s1, string s2) { if (s1 == "0" || s2 == "0") { return "0"; } if (s1.length() < s2.length()) { swap(s1, s2); } string s3; for (int i = 0; i < s2.length(); ++i){ string t = sMc(s1, s2[s2.length() - 1 - i]); s3 = sAs(s3, t + string(i, '0')); } return s3;}int main(){ string s1, s2, s3; cin >> s1 >> s2; s3 = sMs(s1, s2); cout << s3 << endl; //system("pause"); return 0;}