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

题解:

我们小时候都学过多位数的乘法过程,都是每位相乘然后错位相加,那么这里就是用到这种方法,把错位相加后的结果保存到一个一维数组中,然后分别每位上算进位,最后每个数字都变成一位,然后要做的是去除掉首位0,最后把每位上的数字按顺序保存到结果中即可,

为了避免溢出,显然应该考虑对应位相乘,求结果的每一位的值最后串在一起。 
比如,217*561,个位=7*1,十位=1*1+7*6,百位 = 7*5+1*6+2*1,千位=2*6+1*5,万位=2*5。分别存进数组里面,在考虑低位向高位的进位。转换为字符串之后考虑首位为0的情况。

    //43.字符串数字相乘
    public String multiply(String num1,String num2){
    	//字符串反转
    	num1=new StringBuilder(num1).reverse().toString();
    	num2=new StringBuilder(num2).reverse().toString();
    	//两数相乘  最大位数为两者位数之和
    	int[] product=new int[num1.length()+num2.length()];
    	for(int i=0;i<num1.length();i++){
    		for(int j=0;j<num2.length();j++)
    			 //先获取对应位相乘  不考虑进位
    			product[i+j]+=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');	   		
    	}
    	//对进位进行处理
    	for(int i=0;i<product.length;i++){
    		if(product[i]>9){
    			product[i+1]+=product[i]/10;
    			product[i]%=10;
    		}
    	}
    	StringBuilder result=new StringBuilder();
    	for(int i=product.length-1;i>=0;i--)
    		result.append(product[i]);
    	 //去除首部的0
    	while(result.charAt(0)=='0'&&result.length()>1)
    		result.deleteCharAt(0);
    	return result.toString();  	
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值