题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
Python
传统方法:小于指数绝对值的情况下,每次乘底数
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
res=1
for i in range(abs(exponent)):
res*=base
if exponent>0:
return res
else:
return 1/res
JAVA
思路一:传统解法
public class Solution {
public double Power(double base, int exponent) {
double res=1.0;
for(int i=0;i<Math.abs(exponent);i++){//注意绝对值不能取
res*=base;
}
return (exponent>0)?res:1/res;
}
}
思路二:利用math.pow()注意底数和指数为1的特殊情况
public class Solution {
public double Power(double base, int exponent) {
if (base==0.0 && exponent==0) return 1.0;//base为double型,exponent为int型
return Math.pow(base,exponent);
}
}
思路三:递归
n为偶数,a^n = a^n/2 * a^n/2;
n为奇数,an=(a(n-1)/2)(a^(n-1/2)) a
时间复杂度O(logn)
觉得有问题
public class Solution {
public double Power(double base, int exponent) {
int n = Math.abs(exponent);
if (n == 0) return 1;
if (n == 1) return base;//觉得-1次方有问题
double res = Power(base, (n >> 1));//右移一位相当于除以2
res *= res;
if ((n & 1) == 1) res *= base;//判断奇数
return exponent > 0 ? res : 1/res;
}
}