| 输入 |
输出 |
| 2 |
1 |
| 3 |
2 |
| 4 |
4 |
| 5 |
6 |
| 6 |
9 |
| 7 |
12 |
| 8 |
18 |
| 9 |
27 |
| 输入 |
输出 |
| 4 |
30*4 |
| 5 |
31*2 |
| 6 |
32 |
| 7 |
31*4 |
| 8 |
32*2 |
| 9 |
33 |
public int cuttingRope(int n) {
if(n==2||n==3)return n-1;
int a = n / 3;
int b = n % 3;
if(b==0) return (int)(Math.pow(3,a));
if(b==1) return (int)(Math.pow(3,a-1)*4);
if(b==2) return (int)(Math.pow(3,a)*2);
return 0;
}
- 如果发生大数越界情况,则需要转为for循环累乘并用long类型保存中间数据,最后再统一取模
public int cuttingRope(int n) {
if(n==2||n==3)return n-1;
int a = n / 3;
int b = n % 3;
long sum = 1;
for(int i = 0;i<a-1;i++){
sum = (long)(sum*3%(1e9+7));
}
if(b==0){
return (int)(sum*3%(1e9+7));
}
if(b==1){
return (int)(sum*4%(1e9+7));
}
if(b==2){
return (int)(sum*6%(1e9+7));
}
return 0;
}