-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
36 lines (34 loc) · 797 Bytes
/
Copy pathSolution.java
File metadata and controls
36 lines (34 loc) · 797 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
package recursion;
class Solution {
public static void main(String[] args) {
double v = new Solution().myPow(2, -2);
System.out.println(v);
}
public double myPow(double x, int n) {
boolean flag = false;
double result = 0;
if( n == 0){
return 1;
}
if( n < 0){
flag = true;
n = 0-n;
}
if (n == 1){
result = x;
}else if(n == 2){
result = x * x;
}else if(n % 2 == 0){
double a = myPow(x,n/2);
result = a*a;
}
else if(n % 2 == 1) {
double a = myPow(x,n/2);
result = a*a*x;
}
if(flag){
result = 1/ result;
}
return result;
}
}