Skip to content

Commit bf0ced5

Browse files
author
applewjg
committed
Power-n
Change-Id: I82e6ca7e7b9e6831cb65171e1a21d9380f1a1d3b
1 parent a05ec15 commit bf0ced5

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Pow(x,n).java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Pow(x, n)
5+
Difficulty: easy
6+
Source: https://oj.leetcode.com/problems/powx-n/
7+
Notes:
8+
Implement pow(x, n).
9+
10+
Solution: recursion.
11+
*/
12+
public class Solution {
13+
public double pow(double x, int n) {
14+
if (x < 0) return (n % 2 == 0) ? pow(-x, n) : -pow(-x, n);
15+
if (x == 0 || x == 1) return x;
16+
if (n < 0) return 1.0 / pow(x,-n);
17+
if (n == 0) return 1.0;
18+
if (n == 1) return x;
19+
double half = pow(x,n/2);
20+
if (n % 2 == 0) return half * half;
21+
else return x * half * half;
22+
}
23+
}

0 commit comments

Comments
 (0)