题目描述
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
举例
Input: num1 = “123”, num2 = “456”
Output: “56088”
备注
- The length of both num1 and num2 is < 110.
- Both num1 and num2 contain only digits 0-9.
- Both num1 and num2 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.
解题思路
本题的基本思路为:
将字符串相乘拆解为:(1)字符串与单个字符的相乘(2)字符串之间的相加
举个例子:
num1 = “123”, num2 = “456”
将num1分别和‘6’,‘5’,‘4’相乘,得到“738”,“615”,“492”;然后将“738”,“6150”,“49200”进行字符串相加。
编程实现
public String multiply(String num1, String num2) {
if(num1.equals("0")||num2.equals("0")){
return "0";
}
if(num1.length()<num2.length()){
String exchange = num1;
num1=num2;
num2=exchange;
}
StringBuffer result = new StringBuffer();
StringBuffer []singleResult = new StringBuffer[num2.length()];
int decade = 0;
int unit = 0;
int k = 0;
for(int i=num2.length()-1;i>=0;--i){
decade = 0;
char singleCharofNum2 = num2.charAt(i);
StringBuffer result2 = new StringBuffer();
for(int j=num1.length()-1;j>=0;--j){
char singleCharOfNum1 = num1.charAt(j);
int buff = (singleCharOfNum1-'0')*(singleCharofNum2-'0');
int unitBuff = (decade + buff)%10;
int decadeBuff = (decade + buff)/10;
decade = decadeBuff;
unit = unitBuff;
result2.insert(0,unitBuff);
}
if(decade>0){
result2.insert(0,decade);
}
singleResult[k] = result2;
++k;
}
result = singleResult[0];
for(int i=1;i<num2.length();++i){
StringBuffer multiplier = new StringBuffer();
for(int j=0;j<i;++j) {
multiplier = singleResult[i].append('0');
}
result = addStrings2(result,multiplier);
}
return result.toString();
}
public StringBuffer addStrings2(StringBuffer num1, StringBuffer num2) {
StringBuffer result = new StringBuffer();
int carry = 0;
int l1 = num1.length();
int l2 = num2.length();
while(l1>0 || l2 > 0 || carry > 0) {
int tem = carry;
if(l1 > 0) {
l1--;
tem = tem + num1.charAt(l1) - '0';
}
if(l2 > 0) {
l2--;
tem = tem + num2.charAt(l2) - '0';
}
carry = tem/10;
result.append(tem%10);
}
return result.reverse();
}