数值的整数次方

时间:2022-03-31 20:38:10
时间限制:1秒 空间限制:32768K 热度指数:117256 算法知识视频讲解

题目描述

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。思路:要考虑到指数为负数的情形!如果指数是负数,就先求其绝对值,求出n次方后再求倒数
public class Solution {
double sum = 0.0;
public double Power(double base, int exponent) {
if(equal(base,0.0)&&exponent < 0){//如果底数等于0 指数小于0 则返回0.0
sum = 0.0;
}//if
else{
if(exponent>=0){//如果exponent>=则直接调用fun()函数
sum = fun(base,exponent);
}//if
else{
exponent = Math.abs(exponent);
sum = (double)(1/fun(base,exponent));
}//else
}//else
return sum;
}//Power
private double fun(double base,int exponent){
double s = 1.0;
for(int i = 0;i < exponent;i++){
s = s*base;
}
return s;
}//fun
private boolean equal(double num1,double num2){
if((num1 - num2 > -0.00000001)&&(num1 - num2 < 0.00000001))
return true;
else return false;
}//equal
}