File tree 1 file changed +44
-59
lines changed
src/main/java/com/fishercoder/solutions
1 file changed +44
-59
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
- /**
4
- * 50. Pow(x, n)
5
- *
6
- * Implement pow(x, n).
7
-
8
- Example 1:
9
-
10
- Input: 2.00000, 10
11
- Output: 1024.00000
12
-
13
- Example 2:
14
-
15
- Input: 2.10000, 3
16
- Output: 9.26100
17
- */
18
3
public class _50 {
19
4
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
- }
5
+ public static class Solution1 {
6
+ /**
7
+ * Time: O(logn)
8
+ * Space: O(logn)
9
+ */
10
+ public double myPow (double x , int n ) {
11
+ long N = n ;
12
+ if (N < 0 ) {
13
+ x = 1 / x ;
14
+ N = -N ;
15
+ }
16
+ return fastPow (x , N );
17
+ }
33
18
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
- }
19
+ private double fastPow (double x , long n ) {
20
+ if (n == 0 ) {
21
+ return 1.0 ;
22
+ }
23
+ double half = fastPow (x , n / 2 );
24
+ if (n % 2 == 0 ) {
25
+ return half * half ;
26
+ } else {
27
+ return half * half * x ;
28
+ }
29
+ }
44
30
}
45
- }
46
31
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 ;
32
+ public static class Solution2 {
33
+ /**
34
+ * Time: O(logn)
35
+ * Space: O(1)
36
+ */
37
+ public double myPow (double x , int n ) {
38
+ long N = n ;
39
+ if (N < 0 ) {
40
+ x = 1 / x ;
41
+ N = -N ;
42
+ }
43
+ double answer = 1 ;
44
+ double currentProduct = x ;
45
+ for (long i = N ; i > 0 ; i /= 2 ) {
46
+ if (i % 2 == 1 ) {
47
+ answer = answer * currentProduct ;
48
+ }
49
+ currentProduct *= currentProduct ;
50
+ }
51
+ return answer ;
63
52
}
64
- currentProduct *= currentProduct ;
65
- }
66
- return answer ;
67
53
}
68
- }
69
54
}
You can’t perform that action at this time.
0 commit comments