使用累乘 直接暴力求解 复杂度O(n)
运行时间:43ms
占用内存:10564k
public class Solution {
public double Power(double base, int exponent) {
if(exponent==0) return 1;
if(base == 0 && exponent <= 0){
throw new RuntimeException();
}
double result =1;
for(int i=1;i<=Math.abs(exponent);i++){
result=result*base;
}
if(exponent<0) return(1/result);
else return result;
}
}
运行时间:43ms
占用内存:10576k
public class Solution {
public double Power(double base, int exponent) {
double res=1;
if(base==0)
if(exponent<0) throw new RuntimeException();
if(exponent==0)return 1;
if(exponent<0)base=1/base;
while(exponent!=0){
res*=base;
exponent=exponent>0?(--exponent):(++exponent);
}
return res;
}
}
递归运算 ,用右移运算符替代了除以2,用位与运算符代替了求余运算符%来判断一个数是奇数还是偶数。
运行时间:43ms
占用内存:10584k
public class Solution {
public double Power(double base, int exponent) {
if(base==0) if(exponent<0) throw new RuntimeException();
int n = Math.abs(exponent);
if (n == 0) return 1.0;
if (n == 1) return base;
double result = Power(base, n >> 1);
result *= result;
if ((n & 1) == 1) // 如果指数n为奇数,则要再乘一次底数base
result *= base;
if (exponent < 0) // 如果指数为负数,则应该求result的倒数
result = 1 / result;
return result;
}
}