leetcode No43. Multiply Strings

来源:互联网 发布:漏洞提交平台 知乎 编辑:程序博客网 时间:2024/06/05 03:48

Question:

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.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

模拟两个数相乘的结果,两个数用string表示,结果也用string表示

Algorithm:

举个例子:nums1="123",nums2="456"


个位数:nums2[2]*nums1[2]=2*6=18     余数8,进位1

十位数:nums2[2]*nums1[1]+nums2[1]*nums1[2]=6*2+5*3=27             27+1(进位)=28       余数8    进位2

。。。。依次类推,最后得到的结果逆序即可

Aceepted Code:

class Solution {public:    string multiply(string num1, string num2) {        int N1=num1.size();        int N2=num2.size();        string res;        int index=0;        int tmp=0;     //每一位的结果        while(index<(N1+N2+1))        {            int i=0;            while (i<=index)    {    if ((i<N1) && (index - i)<N2)    {    tmp +=( num1[N1-i-1]-'0') * (num2[N2-index+i-1]-'0');    }    i++;    }            res.push_back(tmp%10+'0');            tmp/=10;            index++;        }        reverse(res.begin(),res.end());        string::iterator it=res.begin();        while(*it=='0')        {            res.erase(it);        }        if(res.empty())return "0";          return res;    }};




0 0
原创粉丝点击