Multiply Strings(medium)

【题目】     

   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.
【题意】

      计算大数乘法。其中大数是以字符串的形式表示,任意大,非负,返回结果以字符串形式

【分析】  

      假设两个字符串的长度分别为了a和b,可以得出最后结果长度为a+b(最后有进位)或者a+b-1(最后没有有进位)。由此程序中得先用长度为a+b的数组记录结果,最后再转成字符串。在计算时,先把各个位的相乘结果对应累加起来,例如第1个整数的第i位(低位到高位)和第2个整数的第j位(低位到高位)相乘的结果应该存放在数组的i+j位。然后再统一处理进位。在将数组转换成字符串前,需要跳过前面的零,如果结果只有0,则只返回0。

  注意:乘法计算中可以发现,结果中第i位,应该由第一个字符串中的第1位乘以第二个字符串中的第i位,第一个字符串中的第2位乘以第二个字符串中的第i-1位,.......第一个字符串中的第i位乘以第二个字符串中的第1位,最后累加求得,最后我们取个位上的数值,然后剩下的作为进位放到下一轮循环中  

 //分别对两个开始字符串进行转置,便于后面的下标遍历

【实现】

public String multiply(String num1, String num2) {
    String a = new StringBuilder(num1).reverse().toString();
    String b = new StringBuilder(num2).reverse().toString();
    int[] tem = new int[num1.length()+num2.length()];
 
    for(int i=0; i<a.length(); i++){
        for(int j=0; j<b.length(); j++){
            tem[i+j] += (a.charAt(i)-'0') * (b.charAt(j)-'0');
        }
    }
 
    StringBuilder res = new StringBuilder();
    //计算每一位
    for(int i=0; i<tem.length; i++){
        int mod = tem[i]%10;
        int jinwei = tem[i]/10;
        if(i+1<tem.length){
            tem[i+1] += jinwei;
        }
        res.insert(0, mod);
    }
 
    //remove front 0's
    while(res.charAt(0) == '0' && res.length()> 1){
        res.deleteCharAt(0);
    }
 
    return res.toString();
}

时间复杂度两个字符串长度的乘积,空间复杂度是 两个字符串长度的和

    public String multiply(String num1, String num2) {
        BigInteger n1 = new BigInteger(num1);
        BigInteger n2 = new BigInteger(num2);
     
        return n1.multiply(n2).toString();
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值