Multiply Strings
Total Accepted: 32567 Total Submissions: 155053Given 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;
}
}