avatar

数值的整数次方

题目描述

给定一个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);//向右位移一位,表示除以2,并且在奇数下算作(n-1)/2
result*=result;
if((n&1)==1)
result*=base;//如果是奇数的话再乘以base
if(exponent<0)
result=1/result;
return result;
}
}

第四种思路



文章作者: zenshin
文章链接: https://zlh.giserhub.com/2020/03/11/cl35o0mrh004up4tgg08gbkin/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 zenshin's blog
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论