首页 > 代码库 > Leetcode Pow(x,n)

Leetcode Pow(x,n)

Implement pow(xn).

明显的二分解决

由于n不可能总是偶数,

  如果n是正奇数,那么n个x的乘积等于两部分的乘积再乘以x

  如果n是负奇数,那么n个x的乘积等于两部分乘积再乘以1/x

class Solution {public:    double pow(double x, int n) {        if( n == 0) return 1.0;        double half = pow(x,n/2);        if(n%2 == 0) return half*half;        else if(n > 0 ) return half*half*x;        else return half*half/x;    }};

也可以把负数n直接转换成正数再计算,递归方法:

class Solution {public:    double pow(double x, int n) {        if( n == 0) return 1.0;        if( n == 1) return x;        int exp =abs(n);        double result = (exp%2 == 0) ? pow(x*x,exp/2):pow(x*x,exp/2)*x;        return n < 0 ?1.0/result : result;    }};