-
Notifications
You must be signed in to change notification settings - Fork 2
/
MyPower.java
53 lines (47 loc) · 1.15 KB
/
MyPower.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
package leetcode.math;
public class MyPower {
public double myPow(double x, int n) {
double result = 1;
if (n > 0) {
while (n > 0) {
if (n % 2 == 0) {
x = x * x;
n /= 2;
} else {
result *= x;
n -= 1;
}
}
} else if (n < 0) {
if (n == Integer.MIN_VALUE) {
return myPow(x, n + 1) / x;
}
n = -n;
while (n > 0) {
if (n % 2 == 0) {
x = x * x;
n /= 2;
} else {
result /= x;
n -= 1;
}
}
} else {
return 1;
}
return result;
}
public double myPowSlow(double x, int n) {
double result = 1;
if (n > 0) {
for (int i = 0; i < n; i++) {
result *= x;
}
} else if (n < 0) {
for (int i = 0; i < -n; i++) {
result /= x;
}
}
return result;
}
}