-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11_Power2.cpp
More file actions
85 lines (61 loc) · 1.59 KB
/
Copy path11_Power2.cpp
File metadata and controls
85 lines (61 loc) · 1.59 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
using namespace std;
const double MIN = 0.0000001;
bool g_invalidInput = false;
bool equal(double a, double b)
{
if ((a - b < MIN) && (a -b > -MIN))
return true;
return false;
}
double PowerWithUnsignedExponent(double base, unsigned int exponent)
{
if (equal(base, 0))
return 0;
if (exponent == 0)
return 1.0;
double result = PowerWithUnsignedExponent(base, exponent >> 1);
result = result * result;
if (exponent & 0x01)
result *= base;
return result;
}
double Power(double base, int exponent)
{
g_invalidInput = false;
if (equal(base, 0) && (exponent < 0))
{
g_invalidInput = true;
return 0;
}
int e = exponent;
if (exponent < 0)
e = -exponent;
double result = PowerWithUnsignedExponent(base, e);
if (exponent < 0)
result = 1.0 / result;
return result;
}
int main()
{
cout << Power(0, 0) << endl;
cout << g_invalidInput << endl;
cout << Power(0, 1) << endl;
cout << g_invalidInput << endl;
cout << Power(0, -1) << endl;
cout << g_invalidInput << endl;
cout << Power(2, 10) << endl;
cout << g_invalidInput << endl;
cout << Power(2, -10) << endl;
cout << g_invalidInput << endl;
cout << Power(2, 0) << endl;
cout << g_invalidInput << endl;
cout << Power(-2, 9) << endl;
cout << g_invalidInput << endl;
cout << Power(-2, 0) << endl;
cout << g_invalidInput << endl;
cout << Power(-2, -10) << endl;
cout << g_invalidInput << endl;
cout << Power(16, 1) << endl;
return 0;
}