Sharing my 4ms C++ solution using binary search with time complexity O(log(n))


  • 1
    T
    class Solution {
    private:
        double myPowHelper(double x, long long int n) {
            if(n==0)
                return 1;
            else if(n==1)
                return x;
            else if(n%2==0)
            {
                double temp = myPow(x, n/2);
                return temp*temp;
            }
            else
            {
                double temp=myPow(x, (n-1)/2);
                return temp*temp*x;
            }
        }
        
        
    public:
        double myPow(double x, int n)
        {
            long long int N = (long long int) n;
            if(n>=0)
                return myPowHelper(x, N);
            else
                return myPowHelper((1.0/x), -N);
        }
    };

Log in to reply
 

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