这道题是用brute force做出来的,时间复杂度是O(n) 分n次方的n是正数还是负数2个方面去讨论的.但是leetcode test case: x=0.00001
n=2147483647时,整个程序会超时 Time Limit Exceeded.
public class Solution {
public double myPow(double x, int n) {
if(n==0) return 1;
double target = x;
if(n>0)
{
for(int i=1;i<n;i++){
target = target*x;
}
}
else if(n<0){
for(int i=1;i<-n;i++){
target = target*x;
}
target = 1/target;
}
return target;
}
}
这道题可以用递归来写,x的n次方可以写成x的n/2次方乘以x的n/2次方。代码如下
public class Solution {
public double myPow(double x, int n) {
if(n<0){
return 1/power(x,-n);
}
else{
return power(x,n);
}
}
public double power(double x,int n){
if(n==1) return x;
if(n==0) return 1;
double v = power(x,n/2);
if(n%2==0){
return v*v;
}
else{
return v*v*x;
}
}
}
值得思考的是 递归方法的时间复杂度是多少呢?