数值的整数次方
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
分析
题目本质就是求快速幂
快速幂:
private double pow(double base, int exp) {
if (exp == 0.0 || base == 1.0) return 1.0;
double res = 1.0;
while (exp != 0) {
if ((exp & 1) == 1){
res *= base;
}
base *= base;
exp >>= 1;
}
return res;
}
代码
public class Solution {
public double Power(double base, int exponent) {
if (base == 0.0 && exponent < 0) return 0;
boolean negative = exponent < 0.0;
exponent = Math.abs(exponent);
return negative ? 1 / helper(base, exponent) : helper(base, exponent);
}
private double helper(double base, int exp) {
if (exp == 0.0 || base == 1.0) return 1.0;
double res = 1.0;
while (exp != 0) {
if ((exp & 1) == 1){
res *= base;
}
base *= base;
exp >>= 1;
}
return res;
}
}