topic
Given a float base of type double and an integer exponent of type int. Find the exponent power of base.
Make sure that base and exponent are not 0 at the same time
analyze
Idea one:
Code:
public class Solution {
public double Power(double base, int exponent) {
double res = 1;
int curExp;
if(exponent > 0) {
curExp = exponent;
} else if (exponent < 0) {
if(base == 0) {
throw new RuntimeException("基数不能为0");
}
curExp = -exponent;
} else {
return 1;
}
while(curExp != 0) {
if((curExp & 1) == 1) {
res *= base;
}
base *= base;//翻倍
curExp >>= 1;
}
return exponent > 0 ? res : (1/res);
}
}