Implement pow(x, n).
Subscribe to see which companies asked this question
【方法一】:
1)最直观容易想到的方法就是用递归方法求n个x的乘积,注意考虑n的正负号,时间复杂度为O(n)
double pow(double x, int n)
{
if(n==0)
return 1.0;
if(n<0)
return 1.0/pow(x,-n);
return x*pow(x,n-1);
}
pow(x,n) = pow(x,n/2)*pow(x,n-n/2)
double myPow(double x, int n)
{
// Start typing your C solution below
// DO NOT write int main() function
if(n == 0)
return 1.0;
else if(n > 0)
{
double half = (double)pow(x, n/2);
if(n%2 == 0)
return half*half;
else
return half*half*x;
}
else
{
n = -n;
double half = (double)pow(x, n/2);
if(n%2 == 0)
return 1.0/(half*half);
else
return 1.0/(half*half*x);
}
}
#define INT_MIN_FLAG -2147483648
#define INT_MAX_FLAG 2147483647
/*优化上述 n = -n 存在的Bug*/
double myPow(double x, int n)
{
// Start typing your C solution below
// DO NOT write int main() function
if(n == 0)
return 1.0;
else if(n > 0)
{
double half = (double)myPow(x, n/2);
if(n%2 == 0)
return half*half;
else
return half*half*x;
}
else
{
if(n==INT_MIN_FLAG) {
double half = (double)myPow(x, n/2);
return 1.0/(half*half);
}
n = -n;
double half = (double)myPow(x, n/2);
if(n%2 == 0)
return 1.0/(half*half);
else
return 1.0/(half*half*x);
}
}