[LeetCode] 50. Pow(x, n) Java
题目:
Implement pow(x, n).
Example 1:
Input: 2.00000, 10 Output: 1024.00000
Example 2:
Input: 2.10000, 3 Output: 9.26100
题意及分析:实现求x的n次方,使用分治法,复杂度降低到log2n
代码:
public class Solution { public double myPow(double x, int n) { if(n < 0) return 1/pow(x,-n); else return pow(x,n); } private double pow(double x, int n) { //计算x的n次方 if(n==0) return 1.0; double tmp=pow(x,n/2); if(n%2==0) return tmp*tmp; else return tmp*tmp*x; } }