topic:
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
answer:
Solution one:
Direct use of library functions Math.pow (), the following code:
public class Solution {
public double Power(double base, int exponent) {
return Math.pow(base,exponent);
}
}
Solution two:
Using a loop, one by one, to pay attention to: determine whether the index is negative; Note exponent overflow; code as follows:
public class Solution {
public double Power(double base, int exponent) {
if(exponent==0){
return 1;
}
boolean flag = (exponent>0);
long exp = (long)Math.abs((long)exponent);
double result = 1;
for(long i=0;i<exp;i++){
result = result*base;
}
if(!flag){
result = 1/result;
}
return result;
}
}
Solution three:
Dichotomy, as follows:
public class Solution {
public double Power(double base, int exponent) {
if(exponent==0){
return 1;
}
boolean flag = (exponent>0);
long exp = (long)Math.abs((long)exponent);
double result = 1;
double cur = base;
for(long i=exp;i>0;i=i/2){
if(i%2==1){
result = result*cur;
}
cur = cur*cur;
}
if(!flag){
result = 1/result;
}
return result;
}
}