Skip to content

Commit 0732ead

Browse files
Pow(x, n) : Accepted
1 parent a5724dd commit 0732ead

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ My accepted leetcode solutions to some of the common interview problems.
3232
- [Sqrt(x)](problems/src/binary_search/SqrtX.java) (Easy)
3333
- [Search Insert Position](problems/src/binary_search/SearchInsertPosition.java) (Easy)
3434
- [Median of Two Sorted Arrays](problems/src/binary_search/MedianOfTwoSortedArrays.java) (Hard)
35+
- [Pow(x, n)](problems/src/binary_search/PowXN.java) (Medium)
3536

3637
#### [Bit Manipulation](problems/src/bit_manipulation)
3738

problems/src/binary_search/PowXN.java

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

0 commit comments

Comments
 (0)