大数相乘

c++实现大数相乘问题
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>

using namespace std;

string multiply( string A,  string B)
{
    int m = A.size();
    int n = B.size();
    if (m == 0 || n == 0)
    return string();

    string result(m+n, '0');

    int multiFlag; // 乘积进位
    int addFlag;   // 加法进位
    for(int i=n-1; i >= 0; i--) // B的每一位
    {
        multiFlag = 0;
        addFlag = 0;
        for(int j=m-1; j >= 0; j--) // A的每一位
        {
            // '0' - 48 = 0
            int temp1 = (A[j] - 48) * (B[i] - 48) + multiFlag;
            multiFlag = temp1 / 10;
            temp1 = temp1 % 10;
            int temp2 = (result[i+j+1] - 48) + temp1 + addFlag;
            addFlag = temp2 / 10;
            result[i+j+1] = temp2 % 10 + 48;
        }
        result[i] += multiFlag + addFlag;
    }
    auto p = result.find_first_not_of('0');
    if (p != string::npos)
        return result.substr(p);
    return "0";
}


int main()
{
    string A = "";
    string B = "0";
    string res = multiply(A, B);
    cout << res << endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值