[LeetCode-50] Pow(x, n)(数值的整数次方)

Implement pow(xn).

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);
}

2)考虑到n个x相乘式子的对称关系,可以对上述方法进行改进,从而得到一种时间复杂度为O(logn)的方法,递归关系可以表示为

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);
    }
}



你可能感兴趣的:(LeetCode_Medium)