8000 Sync LeetCode submission - Pow(x, n) (java) · thatbeautifuldream/leetcode-sync@1442611 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1442611

Browse files
Sync LeetCode submission - Pow(x, n) (java)
1 parent 172117f commit 1442611

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public double myPow(double x, int n) {
3+
if(n>=0) {
4+
return posPow(x,n);
5+
} else {
6+
return negPow(x,n);
7+
}
8+
}
9+
private double posPow(double x, int n) {
10+
if(n==0) {
11+
return 1;
12+
}
13+
double y = myPow(x,n/2);
14+
if(n%2==0) {
15+
return y*y;
16+
}
17+
else {
18+
return x*y*y;
19+
}
20+
}
21+
private double negPow(double x, int n) {
22+
if(n==-1) {
23+
return 1/x;
24+
}
25+
double y = myPow(x,n/2);
26+
if(n%2==0) {
27+
return y*y;
28+
}
29+
else {
30+
return (1/x)*y*y;
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)
0