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

这个题说数可能是任意的大的非负数,肯定不是让你直接乘起来返回(我干了。。)而是找一个算法来实现这个乘法。

我看了许久。。看了高手一个答案,没看懂0.0 后来发现其实就按照小学学的乘法运算来就行了。。

最重要的一点就是,n长度的数乘以m长度的数,那么乘积肯定是n+m或者n+m-1的长度

比如 123*100=12300   (n+m-1)  500*900=450000  (n+m)

第二点:小学乘法计算法则

你是不是发现,申明一个n+m的数组num,来存中间变量,从上加到下。 中间用一个carry来保存进位是多少,就可以算出来最后的结果??

没有做出来这个题羞愧的你略微思考,列出了如下公式:  

乘积=乘数1的第i位 * 乘数的第j位+ 进位carry+ 数组当前位

进位=乘积/10

数组当前位最终=乘积%10

 

通过两个for循环,不断刷新最终的num数组,全部结束后最后得到了值。

最后将进位可能为0的第一个数组忽略,剩下的转换为字符串返回。

(当然没有想出来也正常。。多推敲推敲,最恨这种题)

    public String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0")) return "0";
        int len1=num1.length();
        int len2=num2.length();
        int product,carry,i,j;
        int[] num= new int[len1+len2];
        for(i=len1-1;i>=0;i--){
            carry=0;
            for(j=len2-1;j>=0;j--){
                product=carry+ (int)(num1.charAt(i)-'0')*(int)(num2.charAt(j)-'0')+num[i+j+1];
                num[i+j+1]=product%10;
                carry=product/10;
            }
            num[i+j+1]=carry;
        }
         i=0;
        while(i<len1+len2 && num[i]==0){
            i++;
        }
        StringBuilder sb=new StringBuilder();
        while(i<len1+len2){
            sb.append(num[i]);
            i++;
        }
        
        return sb.toString();
    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值