首页 > 代码库 > [leetcode]Pow(x, n)

[leetcode]Pow(x, n)

问题描述:

Implement pow(x, n).

基本思想:

将求幂转换为求对数的幂 . 如x^n = exp(n*log(x));

代码:

double pow(double x, int n) {  //C++
        if(x == 0.0)
            return 0;
        if(n == 0)
            return 1.0;
        
        bool isneg = false;
        if(x < 0 ){
            x = -x;
            if(n%2 == 1)
                isneg =true;    
        }
        double result = exp(n*log(x));
        if(isneg)
            result = -result;
        return result;
        
    }


[leetcode]Pow(x, n)