描述
高精度乘法
输入:两行,每行表示一个非负整数(不超过10000位)
输出:两数的乘积。
样例输入:
99
101
Copy
样例输出:
9999
Copy
限制
各个测试点1s
#include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> using namespace std; #define Max 10001 void BigMul(string A, string B) { int a[Max] = {0}, b[Max] = {0}, sum[Max*2] = {0}; int length_a = A.length(); int length_b = B.length(); for(int i = 1, j = length_a-1; i <= length_a; i++, j--) a[i] = A[j] - '0'; for(int i = 1, j = length_b-1; i <= length_b; i++, j--) b[i] = B[j] - '0'; memset(sum, 0, sizeof(sum)); int length_sum = 0; for(int i = 1; i <= length_a; i++) //用数组模拟运算 { for(int j = 1, t = i-1; j <= length_b; j++) { sum[++t] += b[j]*a[i]; length_sum = t; } } for(int i = 1; i <= length_sum; i++) //进位处理 { if(sum[i] >= 10) { if(sum[length_sum] >= 10) length_sum++; sum[i+1] += sum[i]/10; sum[i] %= 10; } } while(sum[length_sum] == 0 && length_sum != 1) //高位去零 length_sum--; for(int i = 1, j = length_sum; i <= length_sum; i++, j--) cout << sum[j]; } int main() { string A, B; while(cin >> A >> B) BigMul(A, B); return 0; }