数值的整数次方
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
public class OngoingTimesSquare{ public static double Power(double base,int exponent){ if(exponent < 0 ){ exponent = - exponent; return 1/solve(base,exponent); } renturn solve(base,exponent); } public double solve(double base, int exponent){ if(exponent==0) return 1; if(exponent%2==1){ return base*solve(base,(exponent-1)/2)*solve(base,(exponent-1)/2); }else{ return solve(base,exponent/2)*solve(base,exponent/2); } } }
或者 找到更好的答案,当时脑子想了下差点也用的a的b次方 可以根据b的数值循环一下相乘就好了
public double Power(double base, int exponent) { if(exponent == 0){ return 1; }else if(exponent > 0){ double num = base; for(int i = 1; i < exponent; i++){ num = num * base; } return num; }else { double nums = base; int flag = -exponent; for(int i = 1; i < flag; i++){ nums = nums * base; } return 1/nums; } } }