题目:
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; } }
原文地址:https://www.cnblogs.com/271934Liao/p/8335156.html
时间: 2024-10-12 11:32:57