topic
Given a floating-point base of type double and an integer exponent of type int. Find the exponent power of base.
Ensure that base and exponent are not 0 at the same time
answer
1. Use built-in functions
/**
* 使用内置函数
*
* @param base
* @param exponent
* @return
*/
public double Power(double base, int exponent) {
return Math.pow(base, exponent);
}
2. Violence Law
Violent law: direct multiplication
Note :
If the power is negative, we rewrite it as the exponent square of the original number
Processing code :
if (exponent < 0) {
//如果为负数,需要进行处理
base = 1 / base;
exponent = -1 * exponent;
}
Complete code
/**
* 暴力法:直接相乘
*
* @param base
* @param exponent
* @return
*/
public double Power2(double base, int exponent) {
//1、判断次方的正负
if (exponent == 0) return 1.0;
if (exponent < 0) {
//如果为负数,需要进行处理
base = 1 / base;
exponent = -1 * exponent;
}
double sum = 1.0;
//直接循环即可
for (int i = 0; i < exponent; i++) {
sum *= base;
}
return sum;
}
3. Recursion method (power exponent)
/**
* 递归法:快速幂
*
* @param base
* @param exponent
* @return
*/
public double Power3(double base, int exponent) {
if (exponent == 0) return 1.0;
if (exponent < 0) {
//先对次方做处理
exponent = -1 * exponent;
base = 1 / base;
}
return q_power(base,exponent);
}
public double q_power(double b, int e) {
if (e == 0) return 1.0;
double ret = Power3(b, e / 2);
if (e % 2 == 0) {
//偶数
return ret * ret;
} else {
//奇数
return ret * ret * b;
}
}