Monday, June 27, 2016

50. Pow(x, n)

In first place, I'm thinking of calling the function twice with x and n/2 each. It is working but it gets TLE because of too many of recursions.

1:  class Solution {  
2:  public:  
3:    double myPow(double x, int n) {  
4:      if (n == 0) return 1.0;  
5:      x = n < 0 ? 1/x : x;  
6:      return helper(x, abs(n));  
7:    }  
8:    double helper(double x, int n) {  
9:      if (n == 1) return x;  
10:      if (n & 1) return x * helper(x, (n-1)/2) * helper(x, (n-1)/2);  
11:      else return helper(x, n/2) * helper(x, n/2);  
12:    }  
13:  };  

Another way is to call the function once as following. Need to deal with two cases where n is even or n is odd. Particularly, be careful about the case where n < 0.

1:  class Solution {  
2:  public:  
3:    double myPow(double x, int n) {  
4:      if (n == 0) return 1;  
5:      double res = myPow(x, n/2);  
6:      if (n % 2 == 0) {  
7:        return res*res;  
8:      } else {  
9:        return n < 0 ? 1/x*res*res : x*res*res;  
10:      }  
11:    }  
12:  };  

No comments:

Post a Comment