A Short and simple solution! 4ms iterative.


  • 0
    Q
    class Solution {
    public:
         double myPow(double x, int n) {
        
        if (x==0)
        {
            if (n==0){return 1;}
            else {return 0;}
        }
         
        if (n==0)
            return 1;
         
        bool pos=true;
        if (n<0)
        {
            pos = false;
            n=abs(n);
        }
         
        double np=x;
        double res=1;
        while (n>0)
        {
            if (n%2==1)
                res = res * np;
            
            np=np*np;
            n=n/2;
        }
     
        return  pos? res:1/res; 
         
    }
    

    };


Log in to reply
 

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