题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
解题思路
-
当exponent为0时,返回1,当exponent大于0,那么循环exponent次,每次对结果乘以base,最终返回结果。当exponent小于0,则循环exponent的绝对值次,每次对结果乘以base,然后对结果取倒数并返回。对于base为0,那么返回0(exponent不能为负数)。
-
当exponent为0时,返回1,对于a b ,可以进行拆分(b要大于0,求其绝对值),有
[ a^b =
egin{cases}
(a^{frac b2})^2, & ext{if $b$ is even} \
(a^{frac b2})^2 cdot a, & ext{if $b$ is odd} \
end{cases}]
实现
- 方法1
public class Solution {
public double Power(double base, int exponent) {
if (base == 0) return 0;
double result = 1;
int absExp = exponent > 0 ? exponent : -exponent;
for (int i = 0; i < absExp; i++){
result *= base;
}
if (exponent < 0) result = 1 / result;
return result;
}
}
- 方法2
public class Solution {
public double Power(double base, int exponent) {
if (base == 0) return 0;
if (exponent == 0) return 1;
int absExp = exponent > 0 ? exponent : -exponent;
double result = Power(base, absExp >> 1);
result *= result;
if ((absExp & 0x1) == 1){
result *= base;
}
if (exponent < 0) result = 1 / result;
return result;
}
}