File tree Expand file tree Collapse file tree 2 files changed +71
-17
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +71
-17
lines changed Original file line number Diff line number Diff line change 1717 */
1818public class _50 {
1919
20- public static class Solution1 {
21- public double myPow (double x , int n ) {
22- if (n == 0 ) {
23- return 1 ;
24- }
25- if (n == Integer .MIN_VALUE ) {
26- ++n ;
27- n = -n ;
28- x = 1 / x ;
29- return x * x * myPow (x * x , n / 2 );
30- }
31- if (n < 0 ) {
32- n = -n ;
33- x = 1 / x ;
34- }
35- return (n % 2 == 0 ) ? myPow (x * x , n / 2 ) : x * myPow (x * x , n / 2 );
36- }
20+ public static class Solution1 {
21+ /**
22+ * Time: O(logn)
23+ * Space: O(logn)
24+ */
25+ public double myPow (double x , int n ) {
26+ long N = n ;
27+ if (N < 0 ) {
28+ x = 1 / x ;
29+ N = -N ;
30+ }
31+ return fastPow (x , N );
32+ }
33+
34+ private double fastPow (double x , long n ) {
35+ if (n == 0 ) {
36+ return 1.0 ;
37+ }
38+ double half = fastPow (x , n / 2 );
39+ if (n % 2 == 0 ) {
40+ return half * half ;
41+ } else {
42+ return half * half * x ;
43+ }
3744 }
45+ }
3846
47+ public static class Solution2 {
48+ /**
49+ * Time: O(logn)
50+ * Space: O(1)
51+ */
52+ public double myPow (double x , int n ) {
53+ long N = n ;
54+ if (N < 0 ) {
55+ x = 1 / x ;
56+ N = -N ;
57+ }
58+ double answer = 1 ;
59+ double currentProduct = x ;
60+ for (long i = N ; i > 0 ; i /= 2 ) {
61+ if (i % 2 == 1 ) {
62+ answer = answer * currentProduct ;
63+ }
64+ currentProduct *= currentProduct ;
65+ }
66+ return answer ;
67+ }
68+ }
3969}
Original file line number Diff line number Diff line change 1+ package com .fishercoder ;
2+
3+ import com .fishercoder .solutions ._50 ;
4+ import org .junit .BeforeClass ;
5+ import org .junit .Test ;
6+
7+ import static org .junit .Assert .assertEquals ;
8+
9+ public class _50Test {
10+ private static _50 .Solution1 solution1 ;
11+ private static _50 .Solution2 solution2 ;
12+
13+ @ BeforeClass
14+ public static void setup () {
15+ solution1 = new _50 .Solution1 ();
16+ solution2 = new _50 .Solution2 ();
17+ }
18+
19+ @ Test
20+ public void test1 () {
21+ assertEquals (1024.00000 , solution1 .myPow (2.00000 , 10 ), 0.00001 );
22+ assertEquals (1024.00000 , solution2 .myPow (2.00000 , 10 ), 0.00001 );
23+ }
24+ }
You can’t perform that action at this time.
0 commit comments