leetcode 43: Multiply Strings

Multiply Strings

Total Accepted: 32567 Total Submissions: 155053

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.

[思路]

[CODE]

public class Solution {
    public String multiply(String num1, String num2) {
        if(num1==null || num2==null || num1.length()==0 || num1.length()==0) return "0";
    	if(num1.equals("0") || num2.equals("0")) return "0";
    	
    	String s1 = new StringBuilder(num1).reverse().toString();
    	String s2 = new StringBuilder(num2).reverse().toString();
    	String strs[] = new String[s2.length()];
    	
    	for(int i=0; i<s2.length(); i++) {
    		strs[i] = multi(s1, s2.charAt(i), i);
    	}
    	StringBuilder res = stringAdd(strs);
    	return res.reverse().toString();
    }
	
    private String multi(String s, char c, int level) {
    	int cur = 0;
    	int carry = 0;
    	StringBuilder res = new StringBuilder();
    	for(int i=0; i<s.length(); i++) {
    		int b = s.charAt(i) - '0';
    		cur = b * (c-'0')  + carry;
    		carry = cur / 10;
    		res.append(cur%10);
    	}
    	if(carry!=0) res.append(carry);
    	while(level-->0) res.insert(0,0);
    	return res.toString();
    }
    
    private StringBuilder stringAdd(String[] strs) {
        StringBuilder sb = new StringBuilder();
        int len = strs[strs.length-1].length();
        int i=0;
        int cur = 0;
        int carry = 0;
        while(i<len) {
            cur = carry;
            for(int j=0; j<strs.length; j++) {
                if(i>=strs[j].length() ) continue;
                cur += strs[j].charAt(i) - '0';
            }
            carry = cur/10;
            sb.append(cur%10);
            ++i;
        }
        if(carry!=0) sb.append(carry);
        return sb;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值