Title Description
Given a double base type and floating-point type int integer exponent. Seeking exponent of the power base.
Ensure the base and exponent are not simultaneously 0
public class Solution {
public double Power(double base, int exponent) {
}
}
Ideas: recursion.
Because (x * x) n / 2 by solving recursive, recursive and n are each reduced by half, so the overall time complexity of the algorithm is O (logN).
achieve:
public class Solution {
public double Power(double base, int exponent) {
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
boolean isNegative = false;
if (exponent < 0){
exponent = -exponent;
isNegative = true;
}
double pow = Power(base * base, exponent / 2);
if (exponent % 2 != 0)
pow = pow * base;
return isNegative ? 1 / pow : pow;
}
}