leetcode43. 字符串相乘 经典大数+和*
【摘要】 43. 字符串相乘
难度中等264
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:
输入: num1 = "1...
难度中等264
给定两个以字符串形式表示的非负整数 num1
和 num2
,返回 num1
和 num2
的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = "2", num2 = "3" 输出: "6"
示例 2:
输入: num1 = "123", num2 = "456" 输出: "56088"
说明:
num1
和num2
的长度小于110。num1
和num2
只包含数字0-9
。num1
和num2
均不以零开头,除非是数字 0 本身。- 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
-
class Solution {
-
/**
-
* 计算形式
-
* num1
-
* x num2
-
* ------
-
* result
-
*/
-
// 计算结果
-
String res = "0";
-
public String multiply(String num1, String num2) {
-
if (num1.equals("0") || num2.equals("0")) {
-
return "0";
-
}
-
-
// num2 逐位与 num1 相乘
-
for (int i = num2.length() - 1; i >= 0; i--) {
-
int carry = 0;
-
// 保存 num2 第i位数字与 num1 相乘的结果
-
StringBuilder temp = new StringBuilder();
-
// 补 0
-
for (int j = 0; j < num2.length() - 1 - i; j++) {
-
temp.append(0);
-
}
-
int n2 = num2.charAt(i) - '0';
-
-
// num2 的第 i 位数字 n2 与 num1 相乘
-
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();
-
}
-
}
文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。
原文链接:fantianzuo.blog.csdn.net/article/details/104367671
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)