题目描述:实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例:输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
Java代码:
class Solution {
public double myPow(double x, int n) {
long N = n;
if(N<0) {
x = 1 / x;
N = -N;
}
double ans = 1;
double current_product = x;
for(long i=N;i>0;i/=2) {
if((i%2)==1) {
ans = ans*current_product;
}
current_product = current_product*current_product;
}
return ans;
}
}