43. Multiply Strings

本文介绍了一种不使用BigInteger库或直接转换为整数的方法来实现两个大数字符串的乘法运算。通过将字符串反转并逐位相乘的方式,有效地避免了溢出问题,并详细展示了其实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
  • 直接乘会溢出,所以每次都要两个single digit相乘,最大81,不会溢出。
  • 比如385 * 97, 就是个位=5 * 7,十位=8 * 7 + 5 * 9 ,百位=3 * 7 + 8 * 9 …
    可以每一位用一个Int表示,存在一个int[]里面。
  • 这个数组最大长度是num1.len + num2.len,比如99 * 99,最大不会超过10000,所以4位就够了。
  • 这种个位在后面的,不好做(10的0次方,可惜对应位的数组index不是0而是n-1),
    所以干脆先把string reverse了代码就清晰好多。
  • 最后结果前面的0要清掉。

public class Solution {
    public String multiply(String num1, String num2) {
        num1 = new StringBuilder(num1).reverse().toString();
    	num2 = new StringBuilder(num2).reverse().toString();
    	
    	int[] d = new int[num1.length() + num2.length()];
    	for(int i=0; i<num1.length(); i++){
    		int a = num1.charAt(i) - '0';
    		for(int j=0; j<num2.length(); j++){
    			int b = num2.charAt(j) - '0';
    			d[i+j] += a*b;
    		}    		
    	}
    	
    	StringBuffer sb = new StringBuffer();
    	for(int i=0; i<d.length; i++){
    		int digit = d[i]%10;
    		int carry = d[i]/10;
    		sb.insert(0, digit);
    		if(carry > 0){
    			d[i+1] += carry;
    		}
    	}
    	
    	while(sb.length() > 0 && sb.charAt(0) == '0'){
    		sb.deleteCharAt(0);
    	}
    	
    	return sb.length() == 0 ? "0" : sb.toString();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值