Skip to content

Commit 630aa85

Browse files
committed
14.剪绳子,快速幂
1 parent fb86e87 commit 630aa85

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

剑指Offer_新版_java/JZ14.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,37 @@ public int cutRope(int target) {
8282
return (int) Math.pow(3, y);
8383
}
8484
}
85+
}
86+
87+
88+
/*
89+
快速幂
90+
*/
91+
public class Solution {
92+
public int cutRope(int target) {
93+
if (target == 2 || target == 3) {
94+
return target - 1;
95+
}
96+
int x = target % 3;
97+
int y = target / 3;
98+
if (x == 1) {
99+
return pow(3, y - 1) * 4;
100+
} else if (x == 2) {
101+
return pow(3, y) * 2;
102+
} else {
103+
return pow(3, y);
104+
}
105+
}
106+
107+
private int pow(int base, int num) {
108+
int res = 1;
109+
while (num > 0) {
110+
if ((num & 1) == 1) {
111+
res *= base;
112+
}
113+
base *= base;
114+
num >>= 1;
115+
}
116+
return res;
117+
}
85118
}

0 commit comments

Comments
 (0)