File tree 2 files changed +37
-0
lines changed
problems/src/binary_search
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -32,6 +32,7 @@ My accepted leetcode solutions to some of the common interview problems.
32
32
- [ Sqrt(x)] ( problems/src/binary_search/SqrtX.java ) (Easy)
33
33
- [ Search Insert Position] ( problems/src/binary_search/SearchInsertPosition.java ) (Easy)
34
34
- [ Median of Two Sorted Arrays] ( problems/src/binary_search/MedianOfTwoSortedArrays.java ) (Hard)
35
+ - [ Pow(x, n)] ( problems/src/binary_search/PowXN.java ) (Medium)
35
36
36
37
#### [ Bit Manipulation] ( problems/src/bit_manipulation )
37
38
Original file line number Diff line number Diff line change
1
+ package binary_search ;
2
+
3
+ /**
4
+ * Created by gouthamvidyapradhan on 23/05/2017.
5
+
6
+ Implement pow(x, n).
7
+
8
+ Solution: Works with O(log n)
9
+ */
10
+ public class PowXN
11
+ {
12
+ /**
13
+ * Main method
14
+ * @param args
15
+ * @throws Exception
16
+ */
17
+ public static void main (String [] args ) throws Exception
18
+ {
19
+ System .out .println (1 / new PowXN ().myPow (2.00000 , -2147483648 ));
20
+ }
21
+
22
+ public double myPow (double x , int n )
23
+ {
24
+ if (n == 0 ) return 1D ;
25
+ long N = n ; //use long to avoid overflow.
26
+ return solve (n < 0 ? (1 / x ) : x , N < 0 ? (N * -1 ) : N );
27
+ }
28
+
29
+ public double solve (double x , long n )
30
+ {
31
+ if (n == 1 ) return x ;
32
+ double val = solve (x , n / 2 );
33
+ return val * val * ((n % 2 ) == 0 ? 1 : x );
34
+ }
35
+
36
+ }
You can’t perform that action at this time.
0 commit comments