[LeetCode]Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

思考:大数相乘,模拟算数运算。

class Solution {

public:

    string multiply(string num1, string num2) {

        if(num1=="0"||num2=="0") return "0";

        int len1=num1.size();

        int len2=num2.size();

        int len=len1+len2;

        string num3(len,'0');

        int i,j;

        for(j=len2-1;j>=0;j--)

        {

            for(i=len1-1;i>=0;i--)

            {

				int temp=(num2[j]-'0')*(num1[i]-'0')+(num3[i+j+1]-'0');

                if(temp>9) num3[i+j+1]=temp%10+'0';

				else num3[i+j+1]=temp+'0';

				num3[i+j]=((num3[i+j]-'0')+temp/10)+'0';

            }

        }

        if(num3[0]!='0') return num3;

        else return num3.substr(1,len-1);

    }

};

  

 

你可能感兴趣的:(LeetCode)