标签:
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
public class Solution {
public double Power(double base, int exponent) {
if (equal(base, 0.0) && exponent < 0) {
return 0.0;
}
int absExp = exponent;
if (exponent < 0){
absExp = -exponent;
}
double result = 1.0;
for (int i = 1; i <= absExp; i++) {
result *= base;
}
if (exponent < 0) {
result = 1.0 / result;
}
return result;
}
public boolean equal(double num1, double num2) {
if ((num1 - num2 > -0.0000001) && (num1 - num2) < 0.0000001) {
return true;
} else {
return false;
}
}
}
通过递归实现,每次次幂翻倍的乘,可以减少乘法计算的次数,但是注意使用递归前仍然要对输入做必要的检查
public double Power01All(double base, int exponent) {
if (equal(base, 0.0) && exponent < 0) {
return 0.0;
}
int absExp = exponent;
if (exponent < 0) {
absExp = -exponent;
}
double result = Power01(base, absExp);
if (exponent < 0) {
result = 1 / result;
}
return result;
}
public double Power01(double base, int exponent) {
if (exponent == 0) {
return 1;
}
if (exponent == 1) {
return base;
}
double result = Power01(base, exponent >> 1);
result *= result;
if ((exponent & 0x1) == 1) {
result *= base;
}
return result;
}
标签:
原文地址:http://www.cnblogs.com/rosending/p/5617441.html