File tree Expand file tree Collapse file tree 2 files changed +23
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -51,4 +51,24 @@ public double myPow(double x, int n) {
51
51
return answer ;
52
52
}
53
53
}
54
+
55
+ public static class Solution3 {
56
+ /**
57
+ * credit: https://leetcode.com/problems/powx-n/solutions/19546/short-and-easy-to-understand-solution/comments/162293
58
+ */
59
+ public double myPow (double x , int n ) {
60
+ if (n == 0 ) {
61
+ return 1 ;
62
+ }
63
+ if (n < 0 ) {
64
+ //this is to avoid integer overflow
65
+ return 1 / x * myPow (1 / x , -(n + 1 ));
66
+ }
67
+ if (n % 2 == 0 ) {
68
+ return myPow (x * x , n / 2 );
69
+ } else {
70
+ return x * myPow (x * x , n / 2 );
71
+ }
72
+ }
73
+ }
54
74
}
Original file line number Diff line number Diff line change 9
9
public class _50Test {
10
10
private static _50 .Solution1 solution1 ;
11
11
private static _50 .Solution2 solution2 ;
12
+ private static _50 .Solution3 solution3 ;
12
13
13
14
@ BeforeEach
14
15
public void setup () {
15
16
solution1 = new _50 .Solution1 ();
16
17
solution2 = new _50 .Solution2 ();
18
+ solution3 = new _50 .Solution3 ();
17
19
}
18
20
19
21
@ Test
20
22
public void test1 () {
21
23
assertEquals (1024.00000 , solution1 .myPow (2.00000 , 10 ), 0.00001 );
22
24
assertEquals (1024.00000 , solution2 .myPow (2.00000 , 10 ), 0.00001 );
25
+ assertEquals (1024.00000 , solution3 .myPow (2.00000 , 10 ), 0.00001 );
23
26
}
24
27
}
You can’t perform that action at this time.
0 commit comments