-
Notifications
You must be signed in to change notification settings - Fork 0
/
050_PowXN50.java
103 lines (88 loc) · 2.37 KB
/
050_PowXN50.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
class Solution {
public double myPow(double x, int n) {
/*
fast exponentiation method
2 Cases:
n odd
n even
*/
if(n==0){
return 1.0;
}
else if(n==1){
return x;
}
else if(n==-1){
return (1.0/x);
}
if(n%2==0){
return myPow(x*x, n/2);
}
else{
if(n<0){
double ans = myPow(x*x, (n+1)/2);
return (1.0/x)*ans;
}
else{
double ans = myPow(x*x, (n-1)/2);
return x*ans;
}
}
}
}
**************************************************************************************************
class Solution {
public double myPow(double x, int n) {
if (n == 0 || x == 1)
return 1;
if (x == -1 && n % 2 == 0)
return 1.0;
else if (x == -1 && n % 2 == 1)
return -1.0;
if (n > 5000000 && x > 1)
return Integer.MAX_VALUE;
else if (n > 5000000 && x < 1 && x > 0)
return 0.0;
if (n < -5000000)
return 0.0;
if (n == -1.00000)
return 1 / x;
double ans = 1.0;
for (int i = 0; i < Math.abs(n); i++)
ans *= x;
return n > 0 ? ans : 1 / ans;
}
}
************************************************************
class Solution {
public double myPow(double x, int n) {
double ans = 1;
if (n == 0) return 1.0;
double half = myPow(x, n/2);
if (n % 2 == 0) {
return half * half;
} else if (n < 0) {
return (1.0 / x) * half * half;
} else {
return x * half * half;
}
}
}
***********************************************************************
class Solution {
public double myPow(double x, int n) {
if(n == 0)
return 1;
double temp = myPow(x,n/2);
if((n%2 == 0)){
return temp*temp;
}
else{
if(n > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}
}
****************************************************************