大整数乘法

大整数乘法,模拟草稿手算过程,注意做好进位处理即可。

#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;
}

大整数乘法

上一篇:不提供离线安装包,又不会编译,怎么搞qt5.15?


下一篇:【温故Delphi】GAEA用到Win32 API目录