问题描述
Implement pow(x, n).
问题分析
这一题让我们模拟pow(x,n)函数,下面提供一种二分的方法,时间复杂度为O(logn)
代码实现
public double pow(double x, int n) {
if (n == 0) return 1.0;
double half = pow(x, n / 2);
if (n % 2 == 0) {
return half * half;
} else if (n > 0) {
return half * half * x;
} else {
return half / x * half;
}
}
网友评论