Multiply Strings
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"
这题是大数乘法问题, 所以很自然的想到模拟我们平时乘法做法采用拆分乘数,然后乘法累加。
class Solution {
public String multiply(String num1, String num2) {
if(num1.equals("0") || num2.equals("0")){
return "0";
}
int length1 = num1.length();
int length2 = num2.length();
int[] res = new int[length1+length2];
StringBuffer result = new StringBuffer();
for(int i = length1-1; i>=0; i--){
for(int j = length2-1; j>=0; j--){
int mul = (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
int cur = i + j;
int pre = cur + 1;
int sum = mul + res[pre];
res[cur] += sum / 10;
res[pre] = sum % 10;
}
}
for (int i=0; i<res.length; ++i){
if (i==0 && res[i]==0) continue;
result.append(res[i]);
}
return result.toString();
}
}
看到别人用同一种方法写的,但是每次添加位变成[i+j+1], 目的是避免算出的最高位需要进位。
class Solution {
public String multiply(String num1, String num2) {
if(num1.equals("0") || num2.equals("0")){
return "0";
}
int length1 = num1.length();
int length2 = num2.length();
int[] res = new int[length1+length2];
StringBuffer result = new StringBuffer();
for(int i = length1-1; i>=0; i--){
for(int j = length2-1; j>=0; j--){
res[i+j+1] += (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
}
}
for (int i=res.length-1; i>0; i--){
if (res[i]>9){
res[i-1] += res[i]/10;
res[i] %=10;
}
}
for (int i=0; i<res.length; ++i){
if (i==0 && res[i]==0) continue;
result.append(res[i]);
}
return result.toString();
}
}