Multiply strings
Title description: Given two non-negative integers num1 and num2 expressed in string form, return the product of num1 and num2, and their product is also expressed in string form.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/multiply-strings/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: array traversal
- First, if num1 and num2 are 0, return an empty string directly.
- Otherwise, declare a list as temp to record the result of the product of each row;
- Then add up the results of these rows;
- Finally, the accumulated result is returned as a string in reverse order.
import java.util.ArrayList;
import java.util.List;
public class LeetCode_043 {
public static String multiply(String num1, String num2) {
if ((num1 == null || num1.length() == 0) || (num2 == null || num2.length() == 0)) {
return "";
}
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
/**
* 如果num2的长度大于num1的长度将num1和num2的值交换
*/
if (num2.length() > num1.length()) {
String temp = num1;
num1 = num2;
num2 = temp;
}
/**
* 记录每一行的乘积的结果
*/
List<int[]> temp = new ArrayList<>();
int count = 0;
for (int i = num2.length() - 1; i >= 0; i--) {
int c2Num = num2.charAt(i) - '0';
int[] cur = new int[num1.length() + num2.length()];
int index = 0;
for (; index < count; index++) {
cur[index] = 0;
}
int addOne = 0;
for (int j = num1.length() - 1; j >= 0; j--) {
int c1Num = num1.charAt(j) - '0';
if (c2Num * c1Num + addOne > 9) {
cur[index++] = (c2Num * c1Num + addOne) % 10;
addOne = (c2Num * c1Num + addOne) / 10;
} else {
cur[index++] = c2Num * c1Num + addOne;
addOne = 0;
}
}
if (addOne > 0) {
cur[index] = addOne;
}
temp.add(cur);
count++;
}
int addOne = 0;
List<Integer> result = new ArrayList<>();
/**
* 将每一行的乘积结果累加起来
*/
for (int i = 0; i < num1.length() + num2.length(); i++) {
int curNum = addOne;
for (int[] ints : temp) {
curNum += ints[i];
}
if (curNum > 9) {
result.add(curNum % 10);
addOne = curNum / 10;
} else {
result.add(curNum % 10);
addOne = 0;
}
}
String resultStr = "";
int firstNoneZeroIndex = -1;
/**
* 找到第一个不为0的数字
*/
for (int i = result.size() - 1; i >= 0; i--) {
if (result.get(i) != 0) {
firstNoneZeroIndex = i;
break;
}
}
/**
* 将最后的结果拼成string并最后返回
*/
for (int i = firstNoneZeroIndex; i >= 0; i--) {
resultStr += String.valueOf(result.get(i));
}
return resultStr;
}
public static void main(String[] args) {
// 测试用例,预计输出: 56088
System.out.println(multiply("123", "456"));
}
}
[Daily Message] long the road is, you can walk it step by step, and no matter how short it is, you can’t reach it without your feet.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。