-
Notifications
You must be signed in to change notification settings - Fork 257
/
powx-n.cpp
50 lines (48 loc) · 1.04 KB
/
powx-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
38
39
40
41
42
43
44
45
46
47
48
49
50
// Time: O(logn) = O(1)
// Space: O(1)
// Iterative solution.
class Solution {
public:
/**
* @param x the base number
* @param n the power number
* @return the result
*/
double myPow(double x, int n) {
double result = 1;
long long abs_n = abs(static_cast<long long>(n));
while (abs_n > 0) {
if (abs_n & 1) {
result *= x;
}
abs_n >>= 1;
x *= x;
}
return n < 0 ? 1 / result : result;
}
};
// Time: O(logn) = O(1)
// Space: O(logn) = O(1)
// Recursive solution.
class Solution2 {
public:
/**
* @param x the base number
* @param n the power number
* @return the resultult
*/
double myPow(double x, int n) {
if (n < 0 && n != -n) {
return 1.0 / myPow(x, -n);
}
if (n == 0) {
return 1;
}
double v = myPow(x, n / 2);
if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}
};