public class Solution {
/*
//解法一:使用递归 时间复杂度为O(n),空间复杂度为O(n)
public double Power(double base, int exponent) {
if(exponent == 0) {
return 1 ;
}
if(exponent > 0) {
return Power(base , exponent-1) * base ;
} else {//如果 次数为负数,就将次数转换为正数
return Power(1/base , -exponent-1) * (1/base) ;
}
}
*/
//解法二:动态规划+滚动数组 时间复杂度为O(n),空间复杂度为O(1)
public double Power(double base, int exponent) {
if(exponent == 0) {
return 1 ;
}
if(exponent < 0) {//将负次转换为正次
exponent *= -1 ;
base = 1/base ;
}
int old = 0 ;
int now = 1 ;
double dp[] = new double[2] ;//dp[old]= base ^ (i-1) dp[now] = base ^ i
dp[old] = 1 ;
for(int i = 1 ; i <= exponent ; i ++) {
dp[now] = dp[old] * base ;
old = now ;
now = 1-now ;
}
return dp[old] ;
}
}
/*
//解法一:使用递归 时间复杂度为O(n),空间复杂度为O(n)
public double Power(double base, int exponent) {
if(exponent == 0) {
return 1 ;
}
if(exponent > 0) {
return Power(base , exponent-1) * base ;
} else {//如果 次数为负数,就将次数转换为正数
return Power(1/base , -exponent-1) * (1/base) ;
}
}
*/
//解法二:动态规划+滚动数组 时间复杂度为O(n),空间复杂度为O(1)
public double Power(double base, int exponent) {
if(exponent == 0) {
return 1 ;
}
if(exponent < 0) {//将负次转换为正次
exponent *= -1 ;
base = 1/base ;
}
int old = 0 ;
int now = 1 ;
double dp[] = new double[2] ;//dp[old]= base ^ (i-1) dp[now] = base ^ i
dp[old] = 1 ;
for(int i = 1 ; i <= exponent ; i ++) {
dp[now] = dp[old] * base ;
old = now ;
now = 1-now ;
}
return dp[old] ;
}
}