package 数字操作.q43_字符串相乘;
/**
* o(n) 可基于乘数某位与被乘数某位相乘产生结果的位置的规律优化
*/
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
String res = "0";
for (int i = num2.length() - 1; i >= 0; i--) {
int carry = 0;
StringBuilder temp = new StringBuilder();
for (int j = 0; j < num2.length() - 1 - i; j++) {
temp.append(0);
}
int n2 = num2.charAt(i) - '0';
for (int j = num1.length() - 1; j >= 0 || carry != 0; j--) {
int n1 = j < 0 ? 0 : num1.charAt(j) - '0';
int product = (n1 * n2 + carry) % 10;
temp.append(product);
carry = (n1 * n2 + carry) / 10;
}
res = addStrings(res, temp.reverse().toString());
}
return res;
}
public String addStrings(String num1, String num2) {
StringBuilder builder = new StringBuilder();
int carry = 0;
for (int i = num1.length() - 1, j = num2.length() - 1;
i >= 0 || j >= 0 || carry != 0;
i--, j--) {
int x = i < 0 ? 0 : num1.charAt(i) - '0';
int y = j < 0 ? 0 : num2.charAt(j) - '0';
int sum = (x + y + carry) % 10;
builder.append(sum);
carry = (x + y + carry) / 10;
}
return builder.reverse().toString();
}
}
q43_字符串相乘
作品《LeetCode题目分类与面试问题整理 - q43_字符串相乘》由 不喝星巴克 发布于 匠果,转载请注明出处及链接地址:
http://www.jiangguo.net/c/9r6/9d4.html