forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT16.java
More file actions
53 lines (48 loc) · 1.44 KB
/
Copy pathT16.java
File metadata and controls
53 lines (48 loc) · 1.44 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
package books;
/**
* @program JavaBooks
* @description: 数值的整数次方
* @author: mf
* @create: 2019/08/27 09:49
*/
public class T16 {
public static void main(String[] args) {
double value = doublePow(2.0, 8);
System.out.println(value);
}
// 0的0次方没有意义, 所以有个条件限制
private static double doublePow(double number, int exp) {
double result = 1.0;
if (number == 0.0 && exp < 0) return 0.0;
boolean expSign = true;
if (exp < 0) {
expSign = false;
exp = - exp;
}
// result = powerUnsignExp(number, exp);
result = powerUnsignExp2(number, exp);
if (!expSign) {
result = 1 / result;
}
return result;
}
// 效率较低
private static double powerUnsignExp(double number, int exp) {
double result = 1.0;
for (int i = 1; i <= exp; i++) {
result *= number;
}
return result;
}
// 高效率 递归
private static double powerUnsignExp2(double number, int exp) {
if (exp == 0) return 1;
if (exp == 1) return number; // 不管是奇数还是偶数,都会将exp递归到1 都会到这里返回
// 讲究细节
double result = powerUnsignExp2(number, exp >> 1);
result *= result;
// 讲究细节 奇数
if ((exp & 0x1) == 1) result *= number;
return result;
}
}