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 }

 

转载于:https://www.cnblogs.com/lishiblog/p/4125525.html

Logo

昇腾计算产业是基于昇腾系列(HUAWEI Ascend)处理器和基础软件构建的全栈 AI计算基础设施、行业应用及服务,https://devpress.csdn.net/organization/setting/general/146749包括昇腾系列处理器、系列硬件、CANN、AI计算框架、应用使能、开发工具链、管理运维工具、行业应用及服务等全产业链

更多推荐