43. Multiply Strings



题目: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

012
123
645

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值