class Solution {
public int cuttingRope(int n) {
if (n <= 3) {
return n - 1;
}
int a = n / 3;
int b = n % 3;
if (b == 0) {
return (int) Math.pow(3, a);
} else if (b == 1) {
return (int) Math.pow(3, a - 1) * 4;
} else {
return (int) Math.pow(3, a) * 2;
}
}
}
class Solution {
public int cuttingRope(int n) {
if (n==2) {
return 1;
}
if (n==3) {
return 2;
}
int res = n / 3;
int mod = n % 3;
if (mod == 0) {
return pow(3, res);
} else if (mod == 1) {
return pow(3,res - 1) * 4;
} else {
return pow(3, res) * 2;
}
}
public int pow(int a, int n) {
int sum = 1;
int temp = a;
while (n > 0) {
if ((n&1) == 1) {
sum *= temp;
}
temp *= temp;
n = n >> 1;
}
return sum;
}
}
class Solution {
public:
int cuttingRope(int n) {
if (n <= 3) {
return n - 1;
}
int a = n / 3;
int b = n % 3;
if (b == 0) {
return power(3, a);
} else if (b == 1) {
return power(3, a - 1) * 4;
} else {
return power(3, a) * 2;
}
}
long power(unsigned int base, int n) {
long result = 1;
while (n > 0) {
if (n & 1) {
result *= base;
}
base *= base;
n >>= 1;
}
return result;
}
};
共以下 9 个回答
看的答案做的,
‘“java
public int cuttingRope(int n) {
if(n 2) return 1;//长度为2的绳子只能剪1和1
if(n 3) return 2;//长度为3的绳子剪1和2
“`
使用了快速幂算法计算,时间复杂度O(n)
根据题解学习数学
分享一个dp思路
时空复杂度O(1)