题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
思路
第一种思路
java中有计算的api,大家懂我意思吧。这样写虽然能AC,但是我估计会被毙掉,哈哈哈
第二种思路
幂运算就是累乘,所以我们最暴力的方法就是挨个乘起来,这样性能是最差的。
第三种思路
寻找规律,然后根据规律进行递归
借用牛客上面老哥画的图阐述一下了,我们利用这个性质,可以做递归方式来解决这个问题
第四种思路
快速幂算法
代码
第一种思路
public class Main { public static void main(String[] args) { System.out.println(Power(2.13,1)); } public static double Power(double base, int exponent) { return Math.pow(base,exponent); } }
|
第二种思路
public class Main { public static void main(String[] args) { System.out.println(Power(2.13,1)); } public static double Power(double base, int exponent) { if(base == 0) throw new RuntimeException("分母不能为0"); if(exponent == 0) return 1; double result = 1; for(int i=0;i<Math.abs(exponent);i++) { result = result * base; } if(exponent<0) result = 1/result; return result; } }
|
第三种思路
public class Main { public static void main(String[] args) { System.out.println(Power(2.13,1)); } public static double Power(double base, int exponent) { if(exponent==0 && base != 0) return 1; if(exponent==1) return base; if(base == 0 && exponent <= 0){ throw new RuntimeException(); } if(base ==0 && exponent>0){ return 0; } int n= exponent; if(exponent<0){ n = -exponent; } double result=Power(base,n>>1); result*=result; if((n&1)==1) result*=base; if(exponent<0) result=1/result; return result; } }
|
第四种思路