[LeetCode]043-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.

Solution:
思路:
乘数为num1和num2,则模拟手算,每次更新num1位,要加上进位,若需再往前更新,设置个迭代。
代码如下:

 string multiply(string num1, string num2) 
    {
        int len1 = num1.size();
        int len2 = num2.size();
        int len = len1+len2;
        string result(len,'0'); //两数相乘,位数最多len1+len2
        int a,b,c,d,w,k,t,i,j;
        for(i = len1-1;i>=0;i--)
        {
            d = 0;
            for(j = len2-1,k  = len2+i;j>=0;j--,k--)
            {
                a = num1[i] - '0';
                b = num2[j] - '0';
                c  = result[k] - '0';
                t = a*b +c+d;
                result[k] = t %10 + '0'; 

                d = t/10;
                if(j == 0 && d!= 0)
                {
                    w = k-1;
                    t = result[w] - '0' + d;
                    result[w] = t%10 + '0';
                    while(t >=10 && w>0)
                    {
                        result[w] = t %10 +'0';
                        w--;
                        d = t/10;
                        t = result[w] - '0' + d;
                    }
                }
            }
        }
        i = 0;

        while(i < result.size() && result[i] - '0' == 0)
            i++;

        result = result.substr(i,len-i);
        if(result == "")
            return "0";
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值