贪心_剪绳子2

题目

https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof

大数越界问题

解题

贪心 + 快速幂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
public int cuttingRope(int n) {
if (n <= 3) {
return n - 1;
}
int a = n / 3;
int b = n % 3;
if (b == 2) {
return (int) (quickPow(3, a) * b % 1000000007);
} else {
return (int) ((quickPow(3, a - 1) * (b + 3)) % 1000000007);
}
}

// private long quickPow(int x, int n) {
// if (n == 0) {
// return 1;
// }
// long y = quickPow(x, n / 2);
// return (n & 1) == 1 ? (y * y * x) % 1000000007 : (y * y) % 1000000007;
// }

private long quickPow(int x, long n) {
long res = 1;
long tt = x;
while (n != 0) {
if ((n & 1) == 1) {
res *= tt;
res %= 1000000007;
}
tt *= tt;
tt %= 1000000007;
n /= 2;
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int cuttingRope(int n) {
if(n == 2) {
return 1;
}
if(n == 3){
return 2;
}
int mod = (int)1e9 + 7;
long res = 1;
while(n > 4) {
res *= 3;
res %= mod;
n -= 3;
}
return (int)(res * n % mod);
}
}

整数分解

https://leetcode-cn.com/problems/integer-break/solution/343-zheng-shu-chai-fen-tan-xin-by-jyd/

1
2
3
4
5
6
7
8
9
class Solution {
public int integerBreak(int n) {
if(n <= 3) return n - 1;
int a = n / 3, b = n % 3;
if(b == 0) return (int)Math.pow(3, a);
if(b == 1) return (int)Math.pow(3, a - 1) * 4;
return (int)Math.pow(3, a) * 2;
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×