-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPow.java
More file actions
42 lines (32 loc) · 802 Bytes
/
Pow.java
File metadata and controls
42 lines (32 loc) · 802 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
package leetcode;
import org.junit.Test;
import junit.framework.TestCase;
/**
* Link: https://leetcode.com/problems/powx-n/
*
* @author shivam.maharshi
*/
public class Pow extends TestCase {
@Test
public static void test() {
assertEquals(-64.0, myPow(-4, 3));
assertEquals(0.0, myPow(0, 1));
assertEquals(64.0, myPow(4, 3));
assertEquals(1.0, myPow(-4, 0));
assertEquals(0.04, myPow(-5, -2));
}
public static double myPow(double x, int n) {
return n >= 0 ? pow(x, n) : 1 / pow(x, n);
}
public static double pow(double x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
if (n % 2 == 0) {
return pow(x * x, n / 2);
} else {
return pow(x * x, n / 2) * x;
}
}
}