LeetCode 50 Pow(x, n)
Implement pow(x, n), which calculates x raised to the power n (i.e. xn).
public double myPow(double x, int n)
this is actually a classic binary problem.
and the same as sqrt(x)
class Solution {
public double myPow(double x, int n) {
if (n > 0) {
return pow(x, n);
} else {
return 1/pow(x, n);
}
}
private double pow(double x, int n) {
if (n == 0) return 1.0;
double y = pow(x, n/2); //how are we gonna calculate x^n?
if (n % 2 == 0) { //
return y * y;
} else {
return y * y * x;
}
}
}

浙公网安备 33010602011771号