50. Pow(x, n)
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
示例 1:
输入:x = 2.00000, n = 10
输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3
输出:9.26100
示例 3:
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25
提示:
-100.0 < x < 100.0
-231 <= n <= 231-1
-104 <= xn <= 104
class Solution {
public double myPow(double x, int n) {
// 取出n的二进制中最后一个是1的位数
int max = 0;
double result = 1, temp;
if(x == 0){
return 0;
}
if(n == 0){
return 1;
}
if(n < 0){
x = 1 / x;
// 如果次方是最小值,不能直接转化为最大,会出现溢出的问题
if(n != Integer.MIN_VALUE){
n = -n;
} else {
// 转化为正向最大,且手动先算一次方
n = Integer.MAX_VALUE;
result = x;
}
}
while(n != 0){
temp = x;
// 取出了最后一位1的二进制是0010,所以十进制是2
max = (n & (~n + 1));
// 取出来以后可以直接消掉
n = n ^ max;
max = max >> 1;
// 使用几次快速幂乘法
while(max != 0){
temp = temp * temp;
max = max >> 1;
}
result = result * temp;
}
return result;
}
}