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