-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtoThePowerB.java
More file actions
42 lines (35 loc) · 904 Bytes
/
Copy pathAtoThePowerB.java
File metadata and controls
42 lines (35 loc) · 904 Bytes
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
public class AtoThePowerB {
public static void main(String args[]) {
System.out.println(pow(4, 3));
System.out.println(pow(4, -3));
System.out.println(pow(0, 3));
System.out.println(pow(-3, 3));
}
public static double pow(double a, int b) {
if (b == 0) {
return a == 0 ? Integer.MIN_VALUE : 1;
}
if (b == 1) {
return a;
}
if (a == 1) {
return 1;
}
boolean isNegPower=false;
if (b < 0) {
isNegPower = true;
}
double result = powHelper(a, Math.abs(b));
if (isNegPower) {
return 1 / result;
}
return result;
}
private static double powHelper(double a, int b) {
if (b == 1) {
return a;
} else {
return a * powHelper(a, b - 1);
}
}
}