大数相乘

题目描述

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"

示例 2:
输入: num1 = "123", num2 = "456"
输出: "56088"


思路描述

这里以num1为乘数,然后以num2的长度做循环次数,按照普通的乘法加法逻辑,得到最后的结果。

string multiply(string num1, string num2) 
{
    //计算两个字符串所代表的整数相乘,最后结果以字符串的形式返回
    
    if (num1 == "0" || num2 == "0")
        return "0";
    int s1 = num1.length() - 1, s2 = num2.length() - 1;
    int sum = 0;
    int index = 0;
    string s(s1 + s2 + 2, '0');
    //cout << "s " << s << endl;
    //cout << "s.length " << s.length() << endl;
    int s3 = s.length() - 1;
    while (s2 >= 0)
    {
        //cout << "s2 " << s2 << endl;
        s1 = num1.length() - 1;
        sum = 0;
        s3 = s.size() - num2.length() + s2;
        //cout << "s3 " << s3 << endl;
        while (s1 >= 0 || sum != 0)
        {
            //cout << "!!" << endl;
            if (s1 >= 0)
            {
                //cout << "??" << endl;
                sum = (num1[s1] - '0') * (num2[s2] - '0') + (sum % 10) 
                      +  s[s3 - num1.length() + s1 + 1] - '0';
            }
                
            
            //cout << "sum " << sum << endl;
            s[s3 - num1.length() + s1 + 1] = (sum % 10) + '0';
            s1--;
            sum /= 10;
            
            //cout << "s " << s << endl;
        }
        s2--;
        //break;
    }
    
    
    int i = 0;
    for (i = 0; i <= s3; i++)
        if (s[i] != '0')
            break;

    return s.substr(i, s.size());

}

你可能感兴趣的:(大数相乘)