给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

使用累乘 直接暴力求解 复杂度O(n)
运行时间:43ms
占用内存:10564k

public class Solution {
    public double Power(double base, int exponent) {
        
        if(exponent==0) return 1;
        if(base == 0 && exponent <= 0){
            throw new RuntimeException();
        }
        double result =1;     
        for(int i=1;i<=Math.abs(exponent);i++){
            result=result*base;
            
        }
        if(exponent<0) return(1/result);
        else return result;
        
  }
}

运行时间:43ms
占用内存:10576k

public class Solution {
    public double Power(double base, int exponent) {
        double res=1;
        if(base==0)
            if(exponent<0) throw new RuntimeException();
        if(exponent==0)return 1;
        if(exponent<0)base=1/base;
        while(exponent!=0){
            res*=base;
            exponent=exponent>0?(--exponent):(++exponent);
         
        } 
        return res;
  }
}

递归运算 ,用右移运算符替代了除以2,用位与运算符代替了求余运算符%来判断一个数是奇数还是偶数。
运行时间:43ms
占用内存:10584k

public class Solution {
    public double Power(double base, int exponent) {
        if(base==0) if(exponent<0) throw new RuntimeException();
        int n = Math.abs(exponent);
        if (n == 0) return 1.0;
        if (n == 1)  return base;
       double result = Power(base, n >> 1);
        result *= result;
        if ((n & 1) == 1) // 如果指数n为奇数,则要再乘一次底数base
            result *= base;
        if (exponent < 0) // 如果指数为负数,则应该求result的倒数
            result = 1 / result;
         
        return result;
    }
        
  }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值