P1303 A*B Problem
阿新 • • 發佈:2021-11-21
#include <bits/stdc++.h> using namespace std; /** * 功能:高精度乘低精度模板 * @param A * @param b * @return */ vector<int> mul(vector<int> &A, int b) { vector<int> C; int t = 0; for (int i = 0; i < A.size() || t; i++) { if (i < A.size()) t += A[i] * b; C.push_back(t % 10); t /= 10; } while (C.size() > 1 && C.back() == 0) C.pop_back(); return C; } int main() { string a; int b; vector<int> A, C; cin >> a >> b; //倒著放的噢~ for (int i = a.size() - 1; i >= 0; i--) A.push_back(a[i] - '0'); C = mul(A, b); //倒著輸出噢~ for (int i = C.size() - 1; i >= 0; i--) printf("%d", C[i]); return 0; }
//P1303_2.cpp
#include <bits/stdc++.h> using namespace std; /** * 功能:高精度乘高精度模板 * @param A * @param b * @return */ vector<int> mul(vector<int> &A, vector<int> &B) { //初始化大小 vector<int> C(A.size() + B.size()); //先放裡再說 for (int i = 0; i < A.size(); i++) for (int j = 0; j < B.size(); j++) C[i + j] += A[i] * B[j]; //處理餘數 for (int i = 0, t = 0; i < C.size(); i++) { t += C[i]; if (i >= C.size()) C.push_back(t % 10); else C[i] = t % 10; t /= 10; } //去掉前導0 while (C.size() > 1 && C.back() == 0) C.pop_back(); return C; } int main() { string a, b; cin >> a >> b; //準備動作 vector<int> A, B; for (int i = a.size() - 1; i >= 0; i--) A.push_back(a[i] - '0'); for (int i = b.size() - 1; i >= 0; i--) B.push_back(b[i] - '0'); //計算 vector<int> C = mul(A, B); //倒序輸出 for (int i = C.size() - 1; i >= 0; i--) cout << C[i]; return 0; }