字符串相乘
- 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = “2”, num2 = “3”
输出: “6”
示例 2:
输入: num1 = “123”, num2 = “456”
输出: “56088”
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
List<LinkedList<String>> list = new ArrayList<>();
int index = 0;
for (int i = num1.length() - 1; i >= 0; i--) {
LinkedList<String> subList = new LinkedList<>();
int carry = 0;
for (int j = num2.length() - 1; j >= 0; j--) {
if (j == num2.length() - 1) {
for (int k = 0; k < index; k++) {
subList.add("#");
}
}
int num = Integer.parseInt(String.valueOf(num1.charAt(i))) * Integer.parseInt(String.valueOf(num2.charAt(j))) + carry;
subList.addFirst(String.valueOf(num % 10));
carry = num / 10;
}
if (carry != 0) {
subList.addFirst(String.valueOf(carry));
}
list.add(subList);
index++;
}
String result = "";
int carry = 0;
while (true) {
int sum = 0;
boolean flag = false;
for (LinkedList<String> subList : list) {
if (subList.size() != 0) {
String n = subList.removeLast();
if (!n.equals("#")) {
sum += Integer.parseInt(n);
}
flag = true;
}
}
if (!flag) {
break;
}
sum += carry;
carry = sum / 10;
result = String.valueOf(sum % 10) + result;
}
if (carry != 0) {
result = String.valueOf(carry) + result;
}
return result;
}
}