(java)leetcode-43

Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.


解题思路:

这道题既然不能将string直接转换为整数,又要做乘法,那就只能对两个数的每一位进行相乘,存在一个数组里面,最后对数组进行处理了。

比如我们的456*123,大概可以看成这样:


然后再从后往前对每个值进行更新,将个位数作为当前的值,十位以上的作为进位到数组的前一个量。这样就可以实现乘法运算了。最后把数组中前面的为0的量去掉就可。


public class Solution {
    public String multiply(String num1, String num2) {
        //两个string转为int数组
        if(num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0)
			return "";
        int[] add1 = new int[num1.length()];
        for(int i = 0;i<num1.length();i++)
        	add1[i] = Integer.parseInt(num1.substring(i, i+1));
        int[] add2 = new int[num2.length()];
        for(int i = 0;i<num2.length();i++)
        	add2[i] = Integer.parseInt(num2.substring(i, i+1));
        int[] result = new int[num1.length()+num2.length()-1];
        //进行每一位的相乘
        for(int i = 0;i< add1.length;i++)
        	for(int j = 0;j< add2.length;j++)
        		result[i+j] += add1[i]*add2[j];
        int numx = 0;
        String rs = "";
        //反向更新数组的值,并转为string
        for(int i = result.length-1;i>=0;i--)
        {
        	result[i] += numx;
        	numx = result[i]/10;
        	result[i] = result[i]%10;
        	rs = String.valueOf(result[i]) + rs;
        }
        //去掉前面为0的部分
        if(numx > 0)
        	rs = String.valueOf(numx) + rs;
        int index = 0;
        while(index < rs.length() && rs.charAt(index++) == '0');
        return rs.substring(index-1, rs.length());
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值