P1001大数乘法(模拟乘法累加 - 改进)

大数乘法讲解https://blog.csdn.net/u010983881/article/details/77503519

代码 https://blog.csdn.net/qq_32792879/article/details/59121327 

#include <cstdio>
#include <iostream>
#include <cstring>
#define INF 0x3f3f3f
using namespace std;
string strmultiply(string str1 , string str2)
{
    string strResult = "";
    if(str1=="0"||str2=="0")
    strResult="0";
    int len1 = str1.length();
    int len2 = str2.length();
    int num[500] = {0};
    int i = 0, j = 0;
    for(i = 0; i < len1; i++)
    {
        for(j = 0; j < len2; j++)
        {
            num[len1-1 - i + len2-1 - j] += (str1[i] - '0')*(str2[j] - '0');
        }//len1.len2长度的数字 乘积最多为len1 + len2 -1 的长度 并且下角标从0开始 当i ,j为0时 从num[6]开始 以此类推 
    }
    for(i = 0; i < len1 + len2 -1; i++)
    {
        num[i+1] += num[i] / 10;

        num[i] = num[i] % 10;
    }
    for(i = len1 + len2 - 1; i >= 0 ; i--)
    {
        if(num[i]!=0) break;
    }
    for(j = i; j >= 0; j--)
    {
        strResult += num[j] + '0';
    }
    return strResult;
}
int main()
{
    string s1,s2,s3;
    cin>>s1>>s2;
    s3=strmultiply(s1,s2);
    cout<<s3<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/intmain_S/article/details/90314812
今日推荐