Skip to content

Commit 8f0d7e8

Browse files
authored
Create power.cpp
Beats 100%
1 parent 400defd commit 8f0d7e8

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

power.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
double myPow(double x, int n) {
4+
if (n == 0 || x == 1.0) {
5+
return 1.0;
6+
}
7+
8+
if (n == 1 || x == 0.0) {
9+
return x;
10+
}
11+
12+
if (n == -1) {
13+
return 1.0/x;
14+
}
15+
16+
if (n % 2 == 0) {
17+
return myPow(x * x, n / 2);
18+
} else {
19+
return x * myPow(x, n-1);
20+
}
21+
}
22+
};

0 commit comments

Comments
 (0)