【leetcode】Pow(x, n)

class Solution {
public:

    double powPositive(double x,int n)
    {
        if(n==0)return 1;
        if(n==1)return x;
        
        double tmp;
        if(n%2==0)
        {
            tmp=powPositive(x,n/2);
            return tmp*tmp;
        }
        else
        {
            tmp=powPositive(x,n/2);
            return tmp*tmp*x;
        }
    }

    double pow(double x, int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(n>0)
            return powPositive(x,n);
        else
            return 1.0/powPositive(x,-n);
    }
};

点赞