Leetcode-43 stroke record 06 multiplication of large numbers

Posted by Johnm on Fri, 06 Dec 2019 22:40:51 +0100

Given two non negative integers num1 and num2 in the form of string, the product of num1 and num2 is returned, and their product is also expressed in the form of string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"
Explain:

The length of num1 and num2 is less than 110.
num1 and num2 contain only numbers 0-9.
num1 and num2 do not start with zero, except for the number 0 itself.
You cannot use the large number type of any standard library, such as BigInteger, or convert the input directly to an integer.

My implementation method is to simulate the vertical calculation of multiplication of two numbers, but the speed seems not very good

string multiply(string num1, string num2) {
    int len1 = (num1).size();
    int len2 = (num2).size();
    string pLong = len1>len2?num1:num2;
    string pShor = len1<=len2?num1:num2;
    map<int,vector<int>> iRes;
    for (int iXhbl=pShor.size()-1;iXhbl>=0;iXhbl--)
    {
        int iCarry = 0;//Carry control
        string iResult;
        for (int iXhbl2=pLong.size()-1;iXhbl2>=0;iXhbl2--)
        {
            int iSum=0;
            if (iCarry)
            {
                iSum += iCarry;
                iCarry = 0;
            }
            iSum += (pLong[iXhbl2] - '0')*(pShor[iXhbl]-'0');
            if (iSum >= 10)
                iCarry = iSum/10;
            iResult +=( iSum % 10)+'0';
            int djw = (pShor.size()-1- iXhbl) + 1 + (pLong.size() - 1 - iXhbl2);
            iRes[djw].push_back((iSum % 10));
        }
        if (iCarry)
        {
            int djw = (pShor.size() - 1 - iXhbl) + 1 + pLong.size();
            iRes[djw].push_back((iCarry ));
            iResult += iCarry + '0';
        }
    }
    int iCarry = 0;
    string iRest;
    for (int iXhbl=1;iXhbl<=pLong.size()+pShor.size();iXhbl++)
    {
        if (iRes[iXhbl].size() > 0)
        {
            int iSum = 0;
            for (int iXhbl2=0;iXhbl2< iRes[iXhbl].size();iXhbl2++)
            {
                iSum += iRes[iXhbl][iXhbl2];
            }
            if (iCarry)
            {
                iSum += iCarry;
                iCarry = 0;
            }
            if (iSum >= 10)
                iCarry = iSum / 10;

                iRest = iRest + (char)((iSum % 10) + '0');
        }
    }
    if (iCarry)
    {
        iRest = iRest + (char)((iCarry % 10) + '0');
    }
    std::reverse(iRest.begin(), iRest.end());
    //Remove redundant 0
    int zeroNums=0;
    for (int iXh=0;iXh<iRest.size()-1;iXh++)
    {
        if (iRest[iXh] == '0')
        {
            zeroNums++;
        }
        else
            break;
    }
    iRest.erase(0, zeroNums);
    return iRest;
}

Topics: C++ less