码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Pow(x,n)

时间:2014-11-27 06:44:27      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   on   div   log   

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 }

 

Leetcode-Pow(x,n)

标签:style   blog   io   ar   color   sp   on   div   log   

原文地址:http://www.cnblogs.com/lishiblog/p/4125525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!