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 String multiply(String num1, String num2) {
if (num1 == null || num2 == null)
return null;
String value = "0";
int count = 0;
if(num1.length() > num2.length()){
String tmp = num1;
num1 = num2;
num2 = tmp;
}
for (int i = num1.length() - 1; i >= 0; i--) {
count++;
String res = "";
int tmp = num1.charAt(i) - '0';
if (tmp == 0)
continue;
int pre = 0;
for (int j = num2.length() - 1; j >= 0; j--) {
int tmp2 = num2.charAt(j) - '0';
int product = tmp * tmp2 + pre;
res = product % 10 + res;
pre = product / 10;
}
if (pre != 0)
res = pre + res;
System.out.println("res=" + res);
if (value.length() == 1&&value.charAt(0)-'0'==0) {
value = res;
for(int j = 1;j < count; j ++)
value = value+'0';
continue;
} else {
int tmppre = 0;
String median = "";
int numb = count;
System.out.println(count);
median = value.substring(value.length() - count + 1, value.length());
int t = 0;
for (; t <= value.length()-count; t++) {
int tmp3 = (res.charAt(res.length() - 1 - t) - '0') + (value.charAt(value.length() - count - t) - '0') + tmppre;
median = tmp3 % 10 + median;
tmppre = tmp3 / 10;
}
System.out.println(median);
System.out.println("t="+t);
if(t < res.length()) {
for (int x = res.length()-1-t; x >= 0; x--) {
int tmp3 = (res.charAt(x) - '0') + tmppre;
median = tmp3 % 10 + median;
tmppre = tmp3 / 10;
}
}
if (tmppre != 0)
median = tmppre + median;
value = median;
System.out.println("median=" + median);
}
}
return value;
}
第二种:
public String multiply(String num1, String num2) {
if (num1 == null || num2 == null)
return null;
int len1 = num1.length();
int len2 = num2.length();
if(len1 == 0 || len2 == 0) return "0";
char[] str = new char[len1+len2];//
for(int i = 0; i < str.length; i ++)
str[i] = '0';
for (int i = len1-1; i >= 0; i --) {
int tmp1 = num1.charAt(i)-'0';
int pre = 0;
int j = len2-1, k = len2+i;//
for (; j >= 0 ; j --,k--) {
int tmp2 = num2.charAt(j)-'0';
int tmp = tmp2*tmp1+pre+(str[k]-'0');
str[k] = (char)(tmp%10+'0');
pre = tmp/10;
}
if(pre != 0)
str[k] = (char)(pre+'0');
}
int x = 0;
while (x < str.length&&str[x++]=='0');
return new String(str,x-1,str.length-x+1);
}