C++ easy understand code


  • 0
    W
    class Solution {
    public:
        double pow(double x, int n) {
                if(n<0)return powx(1.0/x,-n);
                else return powx(x,n);
        }
    private:
        double powx(double x,int n)
        {
            if(n==0)return 1;
            double result=1;
            while(n>0)
            {
                if(n%2==1)
                {
                    result*=x;
                    n--;
                }
                else {
                    x*=x;
                    n/=2;
                }
            }
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.