-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpowerlogn.cpp
More file actions
54 lines (52 loc) · 1.07 KB
/
Copy pathpowerlogn.cpp
File metadata and controls
54 lines (52 loc) · 1.07 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
/**
* O(logN)的时间复杂度
* Note:
* 需要记住的是,double类型和float类型是不能直接比较大小的,需要近似比较大小。
*/
#include <iostream>
#include <cassert>
double power(double base, int exponent);
bool eq(double a, double b)
{
if(a-b <0.0000001 | a-b > -0.0000001 )
return true;
return false;
}
double power(double base, int exponent)
{
if(eq(base, 0.0) && exponent >= 0)
return 0.0;
else if(eq(base, 0.0) && exponent < 0)
{
//std::cout<<"The base is zero, and the exponent shouldn't be nagetive interger!"<<std::endl;
return -1;
}
else if(!eq(base, 0.0) && exponent < 0)
{
return 1.0/power(base,-exponent);
}
else
{
double result = 1.0;
while(exponent > 0)
{
std::cout << exponent << std::endl;
if(exponent & 0x01)
{
result *= base;
}
base *= base;
exponent=exponent>>1;
}
return result;
}
}
int main(int argc, char const *argv[])
{
assert(power(0.0, -1) < 0);
assert(eq(power(2.0, -1),0.5));
assert(eq(power(2.0, 2),4));
assert(eq(power(0.0, 3),0) );
assert(eq(power(0.0, 0),0 ));
return 0;
}