-
Notifications
You must be signed in to change notification settings - Fork 147
/
Power11.java
67 lines (57 loc) · 1.41 KB
/
Power11.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.so;
/**
* 第11题
* 求base的exponent次方,不得使用库函数,不需要考虑大数问题
*
* @author qgl
* @date 2017/08/09
*/
public class Power11 {
/**
* 对输入的数进行条件判断后计算结果
*
* @param base
* @param exponent
* @return
* @throws Exception
*/
public static double power(double base, int exponent) throws Exception {
double result = 0.0;
if (equal(base, 0.0) && exponent < 0) {
throw new Exception("0的负数次幂无意义");
}
if (equal(exponent, 0)) {
return 1.0;
}
if (exponent < 0) {
result = powerWithExponent(1.0 / base, -exponent);
} else {
result = powerWithExponent(base, exponent);
}
return result;
}
/**
* 幂计算
*
* @param base
* @param exponent
* @return
*/
private static double powerWithExponent(double base, int exponent) {
double result = 1.0;
for (int i = 1; i <= exponent; i++) {
result = result * base;
}
return result;
}
/**
* 判断两个double型数值是否相等(有误差)
*
* @param num1
* @param num2
* @return
*/
private static boolean equal(double num1, double num2) {
return (num1 - num2 > -0.0000001) && num1 - num2 < 0.0000001;
}
}