Implement pow(x, n).
Example 1:
Input: 2.00000, 10 Output: 1024.00000
Example 2:
Input: 2.10000, 3 Output: 9.26100
这个题目使用位运算会先对来说快一点,其中注意的是,关于0的一些运算edge case;还有int类型的边界值,当int不能满足情况时,可以使用long来替换。
java
class Solution {
public double myPow(double x, int n) {
if (Double.compare(x, 0.0) == 0 && n <= 0) {
return 0;
}
long exp = (long)n;
double temp = getExp(x, Math.abs(exp));
if (n < 0) {
temp = 1 / temp;
}
return temp;
}
private double getExp(double x, long n) {
if (n == 0) {
return 1.0;
}
if (n == 1) {
return x;
}
double res = getExp(x, n >> 1);
res *= res;
if ((n & 0x1) == 1) {
res *= x;
}
return res;
}
}