Skip to content

Commit 4a90809

Browse files
committed
fix: --
1 parent 2c623c8 commit 4a90809

File tree

2 files changed

+87
-2
lines changed

2 files changed

+87
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
.
1818
欢迎大家前来讨论,如果觉得对你的学习有一定的帮助,欢迎点个Star (此仓库每天都会准时更新)- vx联系: xiaoda0423
1919

20-
## 🤨 阶段二十九(571
20+
## 🤨 阶段二十九(572
2121

2222
<details open>
2323
<summary>展开查看</summary>
@@ -28,7 +28,7 @@
2828
- 569.[字符串相加](./js-code/code/字符串相加.js)
2929
- 570.[最长递增子序列](./js-code/code/最长递增子序列.js)
3030
- 571.[最长连续递增序列](./js-code/code/最长连续递增序列.js)
31-
31+
- 572.[最长连续递字符串相乘增序列](./js-code/code/字符串相乘.js)
3232

3333
</details>
3434

js-code/code/字符串相乘.js

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/**
2+
* @param {string} num1
3+
* @param {string} num2
4+
* @return {string}
5+
43. 字符串相乘
6+
*/
7+
var multiply = function(num1, num2) {
8+
let len2 = num2.length;
9+
let sum = []
10+
for (let i = len2 - 1; i >= 0; i--) {
11+
let fill = len2 - i - 1
12+
let product = multi(num1, num2[i], fill)
13+
sum.push(product)
14+
}
15+
let result = sum.reduce((prev, next) => {
16+
return addStrings(prev, next)
17+
})
18+
while (result.length > 1 && result[0] === '0') {
19+
result = result.slice(1)
20+
}
21+
return result
22+
};
23+
24+
function multi(n1, n2, fill) {
25+
fill = fill >= 0 ? fill : 0
26+
let carry = 0
27+
let result = ''
28+
let i = n1.length - 1
29+
while (i >= 0) {
30+
let curr = n1[i]
31+
let product = Number(curr) * Number(n2) + carry;
32+
if (product >= 10) {
33+
let strPro = String(product)
34+
carry = strPro[0] * 1
35+
result = strPro[1] + result
36+
} else {
37+
carry = 0
38+
result = product + result
39+
}
40+
i--
41+
}
42+
if (carry !== 0) {
43+
result = carry + result
44+
}
45+
return result + '0'.repeat(fill)
46+
}
47+
48+
var addStrings = function(num1, num2) {
49+
let len1 = num1.length
50+
let len2 = num2.length
51+
let i = len1 - 1
52+
let j = len2 - 1
53+
let carry = 0
54+
let ans = ''
55+
while (i >= 0 || j >= 0) {
56+
let cur1 = i < 0 ? 0 : num1[i] * 1
57+
let cur2 = j < 0 ? 0 : num2[j] * 1
58+
let { result, nextCarry } = add(cur1, cur2, carry)
59+
carry = nextCarry
60+
ans = result + ans
61+
i--
62+
j--
63+
}
64+
if (carry !== 0) {
65+
ans = carry + ans
66+
}
67+
return ans
68+
}
69+
70+
function add(n1, n2, lastCarry) {
71+
let result = 0
72+
let nextCarry = 0
73+
let num = n1 + n2 + lastCarry
74+
if (num >= 10) {
75+
let strnum = String(num)
76+
result = strnum.slice(1) * 1
77+
nextCarry = strnum.slice(0, 1) * 1
78+
} else {
79+
result = num
80+
}
81+
return {
82+
result,
83+
nextCarry
84+
}
85+
}

0 commit comments

Comments
 (0)