Skip to content

Commit 888b0b5

Browse files
committed
feat: add python and java solution to lcof problem
添加《剑指 Offer》题解:面试题14- II. 剪绳子 II
1 parent 325d727 commit 888b0b5

File tree

3 files changed

+96
-0
lines changed

3 files changed

+96
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# [面试题14- II. 剪绳子 II](这里是题目链接,如:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/)
2+
3+
## 题目描述
4+
给你一根长度为 `n` 的绳子,请把绳子剪成整数长度的 `m` 段(m、n 都是整数,n>1 并且 m>1),每段绳子的长度记为 `k[0],k[1]...k[m]` 。请问 `k[0]*k[1]*...*k[m]` 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为 2、3、3 的三段,此时得到的最大乘积是 18。
5+
6+
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
7+
8+
**示例 1:**
9+
10+
```
11+
输入: 2
12+
输出: 1
13+
解释: 2 = 1 + 1, 1 × 1 = 1
14+
```
15+
16+
**示例 2:**
17+
18+
```
19+
输入: 10
20+
输出: 36
21+
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36
22+
```
23+
24+
**提示:**
25+
26+
- `2 <= n <= 1000`
27+
28+
## 解法
29+
### Python3
30+
```python
31+
class Solution:
32+
def cuttingRope(self, n: int) -> int:
33+
if n < 4:
34+
return n - 1
35+
s1, m = divmod(n, 3)
36+
if m == 1:
37+
s1 -= 1
38+
m = 4
39+
return (pow(3, s1) * (1 if m == 0 else m)) % 1000000007
40+
```
41+
42+
### Java
43+
```java
44+
class Solution {
45+
public int cuttingRope(int n) {
46+
if (n < 4) {
47+
return n - 1;
48+
}
49+
int s1 = n / 3;
50+
int m = n % 3;
51+
if (m == 1) {
52+
s1 -= 1;
53+
m = 4;
54+
}
55+
long res = 1;
56+
while (s1-- > 0) {
57+
res *= 3;
58+
res %= 1000000007;
59+
}
60+
return (int) ((res * (m == 0 ? 1 : m)) % 1000000007);
61+
}
62+
}
63+
```
64+
65+
### ...
66+
```
67+
68+
```
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public int cuttingRope(int n) {
3+
if (n < 4) {
4+
return n - 1;
5+
}
6+
int s1 = n / 3;
7+
int m = n % 3;
8+
if (m == 1) {
9+
s1 -= 1;
10+
m = 4;
11+
}
12+
long res = 1;
13+
while (s1-- > 0) {
14+
res *= 3;
15+
res %= 1000000007;
16+
}
17+
return (int) ((res * (m == 0 ? 1 : m)) % 1000000007);
18+
}
19+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution:
2+
def cuttingRope(self, n: int) -> int:
3+
if n < 4:
4+
return n - 1
5+
s1, m = divmod(n, 3)
6+
if m == 1:
7+
s1 -= 1
8+
m = 4
9+
return (pow(3, s1) * (1 if m == 0 else m)) % 1000000007

0 commit comments

Comments
 (0)