【LeetCode】【JAVA】43. Multiply Strings

43. Multiply Strings

题目

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

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

Example

Input: num1 = “2”, num2 = “3”
Output: “6”

Input: num1 = “123”, num2 = “456”
Output: “56088”

Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

解法

使用二维数组存储竖式过程

代码

	public String multiply(String num1, String num2) {
        String res = "";
        
        if(num1.equals("0") || num2.equals("0"))
            return "0";
        
        if(num1.length() < num2.length()) {
        	String s = num1;
        	num1 = num2;
        	num2 = s;
        }
        
        int[][] mul = new int[num2.length()][num1.length()*2];
        int jinwei = 0;
        
        for(int i = 0; i < num2.length(); i++) {
        	int x = (int)(num2.charAt(num2.length()-i-1) - '0');
        	for(int j = 0; j < num1.length(); j++) {
        		int y = (int)(num1.charAt(num1.length()-j-1) - '0');
        		int z = x * y + jinwei;
        		jinwei = z / 10;
        		mul[i][num1.length()*2 - 1 - j - i] = z % 10;
        	}
        	mul[i][num1.length() - 1 - i] = jinwei;
        	jinwei = 0;
        }
        
//        for(int i = 0; i < num2.length(); i++) {
//        	for(int j = 0; j < num1.length()*2; j++) {
//        		System.out.print(mul[i][j] + " ");
//        	}
//        	System.out.println();
//        }
        
        for(int col = num1.length()*2-1; col >= 0; col--) {
        	int col_sum = jinwei;
        	for(int row = 0; row < num2.length(); row++) {
        		col_sum += mul[row][col];
        	}
        	jinwei = col_sum / 10;
        	col_sum = col_sum % 10;
        	res = col_sum + res;
        }
        
        int i = -1;
        while(res.charAt(++i) == '0');			// 除去开头的0
        
        return res.substring(i, res.length());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值