-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pow(x, n).cpp
37 lines (34 loc) · 888 Bytes
/
Pow(x, n).cpp
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
// https://oj.leetcode.com/problems/powx-n/
class Solution {
public:
double pow(double x, int n) {
// not a number
volatile double t = x;
if (t != t) {
return x;
}
if (x == 1.0) {
return 1.0;
} else if (x == -1.0) {
return (n % 2 == 0) ? 1.0: -1.0;
}
double result = 1.0;
if (n < 0) {
n = -n;
while (n-- > 0) {
result = result / x;
if (abs(result) < numeric_limits<double>::epsilon()) {
return 0.0;
}
}
} else {
while (n-- > 0) {
result = result * x;
if (abs(result) < numeric_limits<double>::epsilon()) {
return 0.0;
}
}
}
return result;
}
};