Leetcode-Pow(x,n)
2014-11-27 04:58
344 查看
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:
Solution 2:
Another method is to directly take care of the negative power in the recursion function.
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:
public class Solution { public double pow(double x, int n) { if (x==0) return 0; if (n==0) return 1; double res; if (n>0) res = powRecur(x,n); else{ if (n>Integer.MIN_VALUE) res = powRecur(x,-n); else { res = powRecur(x,-(n+1)); res = res*x; } res = 1 / res; } return res; } public double powRecur(double x, int n){ if (n==1) return x; double temp = powRecur(x,n/2); double res = temp*temp; if (n%2==1) res = res*x; return res; } }
Solution 2:
Another method is to directly take care of the negative power in the recursion function.
public class Solution { public double pow(double x, int n) { if (x==0) return 0; if (n==0) return 1; double res; res = powRecur(x,n); return res; } public double powRecur(double x, int n){ if (n==1) return x; if (n==-1) return 1/x; double temp = powRecur(x,n/2); double res = temp*temp; if (n%2==1) res = res*x; if (n%2==-1) res = res*(1/x); return res; } }
相关文章推荐
- [Leetcode]#50 Pow(x, n)
- Pow(x, n) -leetcode
- LeetCode 50 — Pow(x, n)(C++ Java Python)
- [Leetcode] Pow(x, n)
- [Leetcode]Pow(x, n)
- leetcode-Pow(x, n)
- Leetcode: Pow(x,n)
- LeetCode "Super Pow"
- leetcode第一刷_Pow(x, n)
- [leetcode] Pow(x, n)
- Leetcode NO.50 Pow(x, n)
- LeetCode: Super Pow
- LeetCode: pow
- [LeetCode]题解(python):050-Pow(x, n)
- Leetcode19: Pow(x,n)
- leetcode - Pow(x, n)
- LeetCode | Pow(x, n)
- Leetcode -- Pow(x, n)
- 《leetCode》:Pow(x, n)
- [LeetCode]Pow(x, n)