/**
* 求浮点数的整数次幂(不使用 Math.pow() 方法)
* pow(0.99, 365) = 0.025 (每天做少一点,每年积累的仅有40分之一)
* pow(1.01, 365) = 37.78 (每天努力一点,每年收获38倍成果)
*
* @param number double
* @param times int
* @return double
*/
public static double pow(double number, int times) {
// 非正整数处理
if (times == 0) {
return 1;
}
boolean isNegative = times < 0;
if (isNegative) {
times = -times;
}
// 取幂次二进制串
StringBuilder builder = new StringBuilder();
while (times > 0) {
builder.append(times % 2);
times /= 2;
}
String str = builder.toString();
// 计算以2为递增幂次的积
int len = str.length();
double[] record = new double[len];
record[0] = number;
for (int i = 1; i < len; i++) {
record[i] = record[i - 1] * record[i - 1];
}
// 逐项乘积求和
double sum = 1;
for (int i = 0; i < len; i++) {
if ('1' == str.charAt(i)) {
sum *= record[i];
}
}
return isNegative ? 1 / sum : sum;
}