Leetcode-Pow(x,n)

LiBlog發表於2014-11-27

Implement pow(x, n).

Analysis:

x^n = x^(n/2)*x^(n/2) (*x, if n is odd).

NOTE: We need consider n<0, AND if n=Integer.MIN_VALUE, -n is actually larger than Integer.MAX_VALUE by 1, so we cannot simply take -n.

Solution:

 1 public class Solution {
 2     public double pow(double x, int n) {
 3         if (x==0) return 0;
 4         if (n==0) return 1;
 5       
 6         double res;
 7         if (n>0)
 8             res = powRecur(x,n);
 9         else{
10             if (n>Integer.MIN_VALUE)
11                 res = powRecur(x,-n);
12             else {
13                 res = powRecur(x,-(n+1));
14                 res = res*x;
15             }
16             res = 1 / res;
17         }
18         return res;
19         
20     }
21 
22     public double powRecur(double x, int n){
23         if (n==1) return x;
24 
25         double temp = powRecur(x,n/2);
26         double res = temp*temp;
27         if (n%2==1) res = res*x;
28         return res;
29     }
30 }

Solution 2:

Another method is to directly take care of the negative power in the recursion function.

 1 public class Solution {
 2     public double pow(double x, int n) {
 3         if (x==0) return 0;
 4         if (n==0) return 1;
 5       
 6         double res;
 7         res = powRecur(x,n);
 8         return res;
 9         
10     }
11 
12     public double powRecur(double x, int n){
13         if (n==1) return x;
14         if (n==-1) return 1/x;
15 
16         double temp = powRecur(x,n/2);
17         double res = temp*temp;
18         if (n%2==1) res = res*x;
19         if (n%2==-1) res = res*(1/x);
20         return res;
21     }
22 }

 

相關文章