-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0050_myPow.cc
72 lines (66 loc) · 1.29 KB
/
Problem_0050_myPow.cc
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
double myPow(double x, int n)
{
if (n == 0)
{
return 1.0;
}
if (n == INT32_MIN)
{
return (x == 1.0 || x == -1.0) ? 1.0 : 0;
}
double ans = 1;
for (int i = std::abs(n); i != 0; i = i >> 1)
{
if (i & 1)
{
ans *= x;
}
x *= x;
}
return n < 0 ? 1 / ans : ans;
}
double dfs(double x, int n)
{
if (n == 0)
{
return 1.0;
}
else if (n & 1)
{
return (n > 0 ? x : 1.0 / x) * myPow(x * x, n / 2);
}
else
{
return myPow(x * x, n / 2);
}
}
};
void testMyPow()
{
Solution s;
// cout << s.myPow(2.00000, 10)<<endl;
// cout << s.myPow(2.10000, 3)<<endl;
// cout << s.myPow(2.00000, -1)<<endl;
// cout << s.myPow(2.00000, -2)<<endl;
// cout << s.dfs(2.00000, 10) << endl;
// cout << s.dfs(2.10000, 3) << endl;
// cout << s.dfs(2.00000, -1) << endl;
// cout << s.dfs(2.00000, -2) << endl;
EXPECT_EQ_DOUBLE(1024.00000, s.myPow(2.00000, 10));
EXPECT_EQ_DOUBLE(9.26100, s.myPow(2.10000, 3));
EXPECT_EQ_DOUBLE(0.50000, s.myPow(2.00000, -1));
EXPECT_EQ_DOUBLE(0.25000, s.myPow(2.00000, -2));
EXPECT_SUMMARY;
}
int main()
{
testMyPow();
return 0;
}