title: '算法:数值的整数次方' cover: https://img.paulzzh.com/touhou/random?22 categories: 算法题目 date: 1996-07-27 08:00:00 tags: [算法题目, 递归]
<br/>
<!--more-->给定一个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;
}
}