剑指 Offer 14- II. 剪绳子 II
# 剑指 Offer 14- II. 剪绳子 II (opens new window)
# 1.枚举+大数运算
分析:枚举每一种段数,段之间长度越接近得到的结果越好。
难点在于计算长度时会爆int。这里做法是使用BigInteger对象存放计算的长度。
import java.math.BigInteger;
class Solution {
public int cuttingRope(int n) {
//枚举段数
BigInteger max=BigInteger.valueOf(1);
for(int i=2;i<=n;i++){
int res=n%i,sing=n/i;
BigInteger mul=BigInteger.valueOf(1);
for(int j=0;j<i;j++){
int a=res==0?0:(i-j<=res?1:0);
mul=mul.multiply(BigInteger.valueOf(sing+a));
}
max=max.max(mul);
if(max.intValue()!=mul.intValue()) break;
}
return max.mod(BigInteger.valueOf(1000000007)).intValue();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57