Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
需要考虑乘积的长度,以及乘积的每一位对应的是乘数中哪两个数字的乘积。
注意字符串首位出现0的情况,通常情况下至多首位为0,除了一个特殊情况乘数中有0,这样会造成String中多位为0,所以在开头要排除这个可能。
注意JAVA比较字符串相等必须用equals而不能用==;字符转换成int,除了-'0',还需要强制转换(char);char转成String,也要显示转换,使用String.valueOf
class Solution {
public String multiply(String num1, String num2) {
if(num1.equals("0")|| num2.equals("0")) return "0"; int[] product = new int[num1.length()+num2.length()]; //array to save the product
int m1;
int m2;
int p; for(int i = product.length-1; i >= 0; i--){ //iterate each bit of the product
for(int j = num2.length()-1; j>=0; j--){ //iterate each bit of multiplier2
if(i-j-1 < 0) continue;
if(i-j-1 >= num1.length()) break;
m2 = num2.charAt(j)-'0';
m1 = num1.charAt(i-j-1)-'0';
p = m1*m2;
product[i] += p;
}
} //calculate carry
for(int i = product.length-1; i > 0; i--){
if(product[i]<10) continue; product[i-1] += (product[i]/10);
product[i] %= 10;
} //transfrom integer to string
String result;
if(product[0] != 0) {
result = String.valueOf((char) (product[0] + '0'));
}
else result = "";
for(int i = 1; i < product.length; i++){
result += String.valueOf((char) (product[i] + '0'));
} return result;
}
}