Thursday, 17 December 2015

LeetCode Pow(x, n) simple O(logn) solution .

LeetCode Pow(x, n) simple O(logn) solution .

class Solution {

public:

    double myPow(double x, int n) {

      double temp;

       if(n==0)

         return 1;

       if(n==1)

        return x;

       if(n==-1)

        return 1/x;

        temp=myPow(x,n/2);

      if(abs(n)%2==0){  //if n is even

           return temp*temp;

      }

      else   //if n is odd

      {

       if(n>0)

          return x*temp*temp;

        else

          return (1/x)*(temp)*(temp); //if n is negative return 1/x either

      }

    }

};

No comments:

Post a Comment