Multiply Strings
2019-10-22 本文已影响0人
Ukuleler
捕获.PNG
题中要求num1和num2最大可达到110位,因此不能进行整体计算,需要一位一位进行计算,所以按照小学学习的乘法算法用代码实现即可。
两个数相乘,其结果最长不会超过两个数长度之和,因此可提前拟定好结果,每次运算相加即可。代码如下
public class multiply {
public static String multiply(String num1, String num2) {
char[] c1 = num1.toCharArray();
char[] c2 = num2.toCharArray();
char[] cr = new char[c1.length+c2.length];
for(int i=0;i<cr.length;i++){
cr[i]='0';
}
for(int i=c1.length-1;i>=0;i--){
for(int j=c2.length-1;j>=0;j--){
int temp = toInt(c1[i]) * toInt(c2[j]);
if(temp==0)continue;
int location = cr.length-c1.length-c2.length+i+j+1;
int pre=0;
while(temp!=0 || pre!=0){
int remainder = temp%10 + pre;
temp = temp/10;
int tempRes = toInt(cr[location])+remainder;
if(tempRes<10){
cr[location] = toChar(tempRes);
pre=0;
}else {
cr[location] = toChar(tempRes%10);
pre=tempRes/10;
}
location--;
}
}
}
StringBuilder res = new StringBuilder();
boolean f = false;
for(int i=0;i<cr.length;i++){
if(cr[i]!='0' || f){
res.append(cr[i]);
f=true;
}
}
if(res.length()==0)return "0";
return res.toString();
}
private static int toInt(char c){
return c-48;
}
private static char toChar(int c){
return (char)(c+48);
}
public static void main(String[] args) {
System.out.println(multiply("123","0"));
}
}