-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPowerMath.java
50 lines (46 loc) · 1.36 KB
/
PowerMath.java
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
package SwordToOffer;
/**
* Created by tlh on 2017/3/11.
*/
public class PowerMath {
public static void main(String[] args) {
System.out.println(Power(2, -1));
}
public static double Power(double base, int exponent) {
if (exponent < 0 && base == 0)
throw new RuntimeException("Invalid input");
if (base == 0)
return 0;
double result;
if (exponent < 0) {
result = 1.0 / PowerWithUnSign(base, -exponent);
} else {
result = PowerWithUnSign(base, exponent);
}
return result;
}
public static double PowerWithUnSign(double base, int exponent) {
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
double result = PowerWithUnSign(base, exponent >> 1);
result *= result;
if ((exponent & 0x1) == 1)
result *= base;
return result;
}
public static double PowerFast(double base, int exponent) {
if (exponent < 0 && base == 0)
throw new RuntimeException("Invalid input");
int exp = Math.abs(exponent);
int result = 1;
while (exp != 0) {
if ((exp & 1) == 1)
result *= base;
base *= base;
exp >>= 1;
}
return exponent < 0 ? 1.0 / result : result;
}
}