Multiply Strings

来源:互联网 发布:淘宝七星彩摇奖机 编辑:程序博客网 时间:2024/06/05 09:45

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.

题目描述没有什么太大 的问题 就是一道明显的 高精度乘法题,我们之前也有做过。

高精度的乘法,最主要的一点是知道anw[i+j-1]=a[i]*b[j]+anw[i+j-1];

可能一开始的时候不好想到这个问题,但是将每一位数当作所在的位数来看就容易想到,一个十位数乘上一个十位数,也就是a*10与b*10的乘积,其实就是a*b*10^2。即在不讨论a*b的值的情况下,都是在所在的位数代表的10的次方相乘的位数上,所以我们可以得到上面的式子。

当我们将所有的乘法得到的值都得到以后,就需要面对进位的问题,而这个问题很好解决,就是将得到的答案数组,从低位到高位扫描一遍,然后得到的%10就是当前位的值,/10就是进位的值,但是要注意的是结束条件,因为有可能将所有的位数都扫过以后,却还有进位的存在,就需要在高位多加一个位数。

在输出的时候将数组转化为string输出,要注意有可能在高位出现零,这些部分是需要删除的。

解决代码如下:

class Solution {public:    string multiply(string num1, string num2) {    int len1=num1.length(), len2=num2.length();        string str="";        int a[1000],b[1000],anw[3000];        int j=0;        for(int i=len1;i>=1;i--)   {   a[i]=num1[j]-'0';   j++;  }  j=0;        for(int i=len2;i>=1;i--)        {   b[i]=num2[j]-'0';         j++;  }                for(int i=1;i<300;i++)        anw[i]=0;          for(int i=1;i<=len1;i++)  for(int j=1;j<=len2;j++)  {   anw[j+i-1]+=a[i]*b[j];  }   int over=anw[1]/10;  anw[1]=anw[1]%10;  int len;         for(len=2;over||len<=len1+len2-1;len++)        {           anw[len]+=over;         over=anw[len]/10;         anw[len]=anw[len]%10;           }        int count=0;        for(int i=len-1;i>0;i--)        {         if(anw[i]==0)         count++;         else         break;  }        if(count==len-1)        count--;        for(int i=len-1-count;i>0;i--)        {         string s="0";         s[0]+=anw[i];         str+=s;  }        return str;    }};

0 0
原创粉丝点击