50. Pow(x, n)
为保证权益,题目请参考 50. Pow(x, n)(From LeetCode).
解决方案1
CPP
C++
/*
* LeetCode 50. Pow(x, n)
* Author: Keven Ge
* Date: 2020-05-11
*/
#include <iostream>
#include <cmath>
using namespace std;
//class Solution {
//public:
// double myPow(double x, int n) {
// return pow(x,n);
// }
//};
class Solution {
public:
/*
* 使用快速幂方法
*/
double myPow(double x, int n) {
long long n2 = n;
bool flag = false;
if (n2 < 0) {
flag = true;
n2 = -n2;
}
double res = 1;
double tmp = x;
unsigned t = 1;
for (int i = 0; i <= 31; ++i) {
if (t & n2) {
res *= tmp;
}
tmp = tmp * tmp;
t = t << 1;
}
if (flag) {
return 1 / res;
} else {
return res;
}
}
};
int main() {
Solution so;
cout << so.myPow(2, -2) << endl;
return 0;
}
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
51
52
53
54
55
56
57
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
51
52
53
54
55
56
57