43. 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.
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
Example
Input: num1 = “2”, num2 = “3”
Output: “6”
Input: num1 = “123”, num2 = “456”
Output: “56088”
Note:
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.
解法
使用二维数组存储竖式过程
代码
public String multiply(String num1, String num2) {
String res = "";
if(num1.equals("0") || num2.equals("0"))
return "0";
if(num1.length() < num2.length()) {
String s = num1;
num1 = num2;
num2 = s;
}
int[][] mul = new int[num2.length()][num1.length()*2];
int jinwei = 0;
for(int i = 0; i < num2.length(); i++) {
int x = (int)(num2.charAt(num2.length()-i-1) - '0');
for(int j = 0; j < num1.length(); j++) {
int y = (int)(num1.charAt(num1.length()-j-1) - '0');
int z = x * y + jinwei;
jinwei = z / 10;
mul[i][num1.length()*2 - 1 - j - i] = z % 10;
}
mul[i][num1.length() - 1 - i] = jinwei;
jinwei = 0;
}
// for(int i = 0; i < num2.length(); i++) {
// for(int j = 0; j < num1.length()*2; j++) {
// System.out.print(mul[i][j] + " ");
// }
// System.out.println();
// }
for(int col = num1.length()*2-1; col >= 0; col--) {
int col_sum = jinwei;
for(int row = 0; row < num2.length(); row++) {
col_sum += mul[row][col];
}
jinwei = col_sum / 10;
col_sum = col_sum % 10;
res = col_sum + res;
}
int i = -1;
while(res.charAt(++i) == '0'); // 除去开头的0
return res.substring(i, res.length());
}