首页 > 其他 > 详细

大整数乘法

时间:2021-09-01 23:07:14      阅读:20      评论:0      收藏:0      [点我收藏+]

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

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

大整数乘法

原文:https://www.cnblogs.com/zhcpku/p/15207539.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!