大整數乘法
阿新 • • 發佈:2021-08-30
大整數乘法,模擬草稿手算過程,注意做好進位處理即可。
#include <iostream> #include <string> #include <algorithm> using namespace std; string mul(string a, string b) { if (a.size() < b.size()) swap(a, b); reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); string res; for (size_t i = 0; i < b.size(); i++) { int carryIn = 0; for (size_t j = 0; j < a.size(); j++) { if (i+j < res.size()) { char ck = (b[i] - '0') * (a[j] - '0') + (res[i+j] - '0') + carryIn; carryIn = ck / 10; res[i+j] = ck % 10 + '0'; // 到這裡自然就知道上面的if條件了 } else { char ck = (b[i] - '0') * (a[j] - '0') + carryIn; carryIn = ck / 10; res.push_back(ck % 10 + '0'); } } while (carryIn) { res.push_back(carryIn % 10 + '0'); carryIn /= 10; } } reverse(res.begin(), res.end()); return res; } int main() { string a, b; cin >> a >> b; cout << mul(a, b) << endl; return 0; }