43. Multiply Strings

来源:互联网 发布:去黑头收缩毛孔 知乎 编辑:程序博客网 时间:2024/05/22 15:56


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


思路:就是用两个字符串进行乘法计算(数据很大),结果也用字符串表示。

(1)先开辟len1+len2长度的整型空间,初始化为0;

(2)对每一个字符串从头扫描至末尾,然后进行存储;

(3)从len1+len2-1到0开始进位

(4)转换成字符串


例子:123*645=79335

012123645

a[i+j+1],加上1是为了方便前面的进位。

a[1]=a[0+0+1]=1*6=6                                                    先6+1=7                                        7%10=7                                         7/10无进位

a[2]=a[1+0+1]=a[0+1+1]=1*4+6*2=16                          先16+3=19                                    19%10=9                                       19/1=1

a[3]=a[1+1+1]=a[0+2+1]=a[2+0+1]=2*4+1*5+6*3=31  先31+2=33                                     33%10=3                                       33/10=3;

a[4]=a[1+2+1]=a[2+1+1]=2*5+3*4=22         先22加上a[5]的进位1,则22+1=23;             23%10=3作为倒数第二位              23/10=2作为进位

a[5]=a[2+2+1]=3*5=15                                                                                                        15 %10=5作为最后一位                 15/10=1作为a[4]的进位;

所以整数数组是:079335;

转换为字符串,如果第一个为0就不用转换为字符串。


代码:

char* multiply(char* num1, char* num2) {    int i=0,j=0;        if(!num1 || !num2 ) return "";        int len1=strlen(num1);    int len2=strlen(num2);    char a[3];    a[0]='0'+79;    a[1]='0'+80;    a[2]='0'+81;        if( (len1==1 && (*num1)=='0' ) || (len2==1 && (*num2)=='0') ) return "0";            int* ret=(int*)malloc(sizeof(int)*(len1+len2));    memset(ret,0,sizeof(int)*(len1+len2));        char* ret1=(char*)malloc(sizeof(char)*(len1+len2+1));    memset(ret1,'0',(len1+len2+1));        for(i=0;i<len1;i++)    {        int pre=num1[i]-'0';                for(j=0;j<len2;j++)        {            int end=num2[j]-'0';            ret[i+j+1]+=pre*end;         }    }        for(i=len1+len2-1;i>=1;i--)    {        int tmp=ret[i];                ret[i]=tmp%10;        int t=tmp/10;        ret[i-1]=ret[i-1]+t;    }            for(i=0;i<=len1+len2-1;i++)    {        ret1[i]=ret[i]+'0';    }        ret1[i]='\0';    //转换成字符串    if(ret1[0] == '0') return ret1+1;    return ret1;    }



























0 0