Problem
Implement pow(x, n).
Example
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1
Note
You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than 1e-3.
Challenge
O(logn) time
Solution
Update 2018-9
class Solution {
public double myPow(double x, int n) {
if (n == 0) return 1;
double half = myPow(x, n/2);
if (n % 2 == 0) return half*half;
else {
if (n < 0) return 1/x*half*half;
else return x*half*half;
}
}
}
When you see O(logn) time for a obvious O(n) time question, think about binary search and recursion.
Double myPow()
无须考虑n为Integer.MIN_VALUE的情况,直接转化成正数计算倒数。
public class Solution {
public double myPow(double x, int n) {
if (n < 0) return 1/pow(x, -n);
else return pow(x, n);
}
private double pow(double x, int n) {
if (n == 0) return 1;
double val = pow(x, n/2);
if (n % 2 == 0) return val*val;
else return val*val*x;
}
}
Double x
需要注意n = Integer.MIN_VALUE的情况,取负数之后会溢出。
public class Solution {
public double myPow(double x, int n) {
if (n == 0) return 1;
if (n < 0) {
if (n == Integer.MIN_VALUE) {
n++;
return 1/(myPow(x, Integer.MAX_VALUE)*x);
}
n = -n;
x = 1/x;
}
return (n%2 == 0) ? myPow(x*x, n/2): x*myPow(x*x, n/2);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。