https://leetcode.com/problems/multiply-strings/
模拟手动乘法,列竖式
class Solution {
public String multiply(String num1, String num2) {
// guarantee len(num1) > len(num2)
if (num1.length() < num2.length()) {
String t = num1;
num1 = num2;
num2 = t;
}
// simulate human multiply
String[] arr = new String[num2.length()];
for (int i = num2.length() - 1, zero = 0; i >= 0; i--, zero++) {
arr[i] = mul(num1, num2.charAt(i) - '0', zero);
}
StringBuilder result = new StringBuilder();
int carry = 0;
for (int i = arr[0].length() - 1; i >= 0; i--) {
int cur = carry;
for (String a : arr) {
cur += a.charAt(i) - '0';
}
carry = cur / 10;
result.insert(0, cur % 10);
}
// remove leading zero
while (result.length() > 0 && result.charAt(0) == '0') {
result.deleteCharAt(0);
}
return result.length() == 0 ? "0" : result.toString();
}
// 多位数 * 一位数
public String mul(String num, int single, int zero) {
StringBuilder result = new StringBuilder();
int carry = 0;
for (int i = num.length() - 1; i >= 0; i--) {
int cur = carry + (num.charAt(i) - '0') * single;
carry = cur / 10;
result.insert(0, cur % 10);
}
if (carry > 0) result.insert(0, carry);
return result.append("0".repeat(zero)).insert(0, "0".repeat(num.length() * 2 - result.length())).toString();
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sinat_42483341/article/details/121203187
内容来源于网络,如有侵权,请联系作者删除!