Pow(x, n)
My SubmissionsImplement pow(x, n).
class Solution {
public:
double pow(double x, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (fabs(x) < 1e-7 || fabs(x - 1) < 1e-7)
return x;
if (n < 0 ) {
n += 1;//防止负数溢出
return (1.0 / (x*pow(x, -n)));
}
if (n == 0)
return 1.0;
if (n == 1) {
return x;
}
if (n == 2)
return x*x;
return (n %2 == 0 ? pow(pow(x,n/2), 2) : x*pow(pow(x, (n-1)/2), 2));
}
};