Multiply Strings (Java)

31 篇文章 0 订阅
19 篇文章 0 订阅

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.

先把每一位乘出来的数存起来,然后再集体处理进位。

Source

public class Solution {
    public String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0")) return "0";
    	StringBuffer x1 = new StringBuffer(num1);
        StringBuffer x2 = new StringBuffer(num2);
        x1.reverse();	//大数乘法一般都倒过来存,比较好处理 尤其是两个数位数不一样时
        x2.reverse();	//如果不reverse的话 数组第0位存的是最高位
        int[] num = new int[x1.length() + x2.length()];  //相乘,数组要开的大
        
        for(int i = 0; i < x1.length(); i++){
        	int a = x1.charAt(i) - '0';		//***注意减去0
        	for(int j = 0; j < x2.length(); j++){
        		int b = x2.charAt(j) - '0';
        		num[i + j] += a * b;
        		
        	}
        }
        
        StringBuffer res = new StringBuffer();
        for(int i = 0; i < num.length; i++){
        	int temp = num[i] % 10;
        	int carry = num[i] / 10;
        	res.insert(0, temp);	//正着存
        	if(i < num.length - 1) num[i + 1] += carry;
        	
        }
        
        while(res.charAt(0) == '0'){
        	res.deleteCharAt(0);
        }
        return res.toString();
    }
}


Test

   public static void main(String[] args){
    	String num1 = "1";
    	String num2 = "2";
    	System.out.println(new Solution().multiply(num1, num2));
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值