package char3;
public class Power {
boolean g_InvalidInput = false;
double power(double base,int exponent) {
if(exponent < 0 && equal(base,0.0)) {
g_InvalidInput = true;
return 0;
}
int absExponent = exponent;
if(absExponent < 0) {
absExponent = -exponent;
}
double result = powerWithUnsignedExponent(base,absExponent);
if(exponent < 0)
result = 1.0/result;
return result;
}
double powerWithUnsignedExponent(double base,int exponent) {
if(exponent == 0)
return 1;
if(exponent == 1)
return base;
double result = powerWithUnsignedExponent(base,exponent>>1);
result = result * result;
if((exponent & 1)==1) {
result *= base;
}
return result;
}
boolean equal(double a,double b) {
if(Math.abs(a-b)< 0.0001)
return true;
return false;
}
public static void main(String[] args) {
Power p = new Power();
System.out.println(p.power(2, 3));
System.out.println(p.power(-2, 3));
System.out.println(p.power(2, -2));
System.out.println(p.power(0, 2));
System.out.println(p.power(0, -2));
System.out.println(p.power(0, 0));
}
}