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.
Subscribe to see which companies asked this question
首先将两个String转换为int数组,然后一位一位模拟乘法就可以了。
下面是本题的JAVA实现。
public class Solution {
public String multiply(String num1, String num2) {
int[] s1 = new int[num1.length()];
int[] s2 = new int[num2.length()];
int[] res = new int[num1.length() + num2.length()];
for(int i = 0 ; i < num1.length() ;i++){
s1[i] = num1.charAt(num1.length() -1 -i) - '0';
}
for(int i = 0 ; i < num2.length() ;i++){
s2[i] = num2.charAt(num2.length() -1 -i) - '0';
}
int middle = 0 ;
for(int i = 0 ; i < num1.length() + num2.length() ; i ++){
for(int j = 0 ; j <= i ; j++){
if(j < num1.length() && i-j < num2.length()){
middle += s1[j]*s2[i-j] ;
}
}
res[i] = middle % 10;
middle = middle / 10;
}
String str = "";
for(int i = 0,flag = 1 ; i < res.length ; i ++){
if(flag == 1 && res[res.length-1 -i] == 0)
continue;
else{
flag = 0;
str += res[res.length-1 -i];
}
}
return str.equals("") ? "0" : str;
}
}