Multiply Strings

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.

 

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

 

你可能感兴趣的:(String)