首页 > 代码库 > Leetcode-Pow(x,n)
Leetcode-Pow(x,n)
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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。