Skip to content

Commit 4a50395

Browse files
update 50
1 parent dff0456 commit 4a50395

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_50.java

+20
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,24 @@ public double myPow(double x, int n) {
5151
return answer;
5252
}
5353
}
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+
}
5474
}

Diff for: src/test/java/com/fishercoder/_50Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,19 @@
99
public class _50Test {
1010
private static _50.Solution1 solution1;
1111
private static _50.Solution2 solution2;
12+
private static _50.Solution3 solution3;
1213

1314
@BeforeEach
1415
public void setup() {
1516
solution1 = new _50.Solution1();
1617
solution2 = new _50.Solution2();
18+
solution3 = new _50.Solution3();
1719
}
1820

1921
@Test
2022
public void test1() {
2123
assertEquals(1024.00000, solution1.myPow(2.00000, 10), 0.00001);
2224
assertEquals(1024.00000, solution2.myPow(2.00000, 10), 0.00001);
25+
assertEquals(1024.00000, solution3.myPow(2.00000, 10), 0.00001);
2326
}
2427
}

0 commit comments

Comments
 (0)