提交 b8441fd9 编写于 作者: Z Zane Wang

为 43-字符串乘法 添加Java解法

上级 8b8f4135
......@@ -101,4 +101,47 @@ string multiply(string num1, string num2) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ No newline at end of file
======其他语言代码======
[Zane Wang](https://github.com/zanecat) 提供 Java 解法代码:
```java
public String multiply(String num1, String num2) {
// 初始化字符数组
char[] s1 = num1.toCharArray();
char[] s2 = num2.toCharArray();
// 结果长度最多为两字符串长度之和
int[] res = new int[s1.length + s2.length];
// 从个位开始遍历,把两数字中每一位相乘
for (int i = s1.length - 1; i >= 0; i--) {
for (int j = s2.length - 1; j >= 0; j--) {
// 计算乘积,并把乘积放在 res 对应的位置, 暂时不考虑进位
res[i + j + 1] += (s1[i] - '0') * (s2[j] - '0');
}
}
// 从个位再次遍历,如果上一次遍历中两数乘积为两位数,进位并叠加到前面一位
int carry = 0;
for (int i = res.length - 1; i >= 0; i--) {
int sum = res[i] + carry;
res[i] = sum % 10;
carry = sum / 10;
}
//遍历res数组,构造最终答案字符串
StringBuilder ans = new StringBuilder();
int i = 0;
// 首先找到不为0的第一位
while (i < res.length - 1 && res[i] == 0) {
i++;
}
// 将后面的数字附加到ans后面
while (i < res.length) {
ans.append(res[i++]);
}
return ans.toString();
}
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册