剑指Offer——题16(数值的整数次方)

1.题目

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

2.实现思路

很容易实现,但需要注意以下陷阱:

  • 0的负数次方不存在;
  • 任意数的0次方为 1;
  • 要考虑exponent为负数的情况。

所以可以对exponent进行分类讨论,在对base是否为0进行讨论。

根据以上公式,减少计算次数,提高效率。

使用右移运算符 >> 代替除以2,有较高的效率:exponent >> 1

使用位与运算符代替求余运算符%判断奇偶数,有较高的效率:if ((exponent & 0x1) == 1)

public class Power {
    public double Power(double base, int exponent) {
         boolean invalid=false;
        double result=-1;

        if(base==0.0&&exponent<=0){
            invalid=true;
            return 0.0;
        }

        if(invalid==false){
            int absexponent=exponent;
            if(exponent<0){
                absexponent=-exponent;
            }
             result=PowerCore(base,absexponent);
            if(exponent<0){
                result=1/result;
            }

        }
        return result;
    }

    private int PowerCore(double base, int exponent) {
        if(base==1){
            return 1;
        }
        if(exponent==0){
            return 1;
        }
        int result=1;
        int count=exponent>>1;
        for(int i=0;i<count;i++){
            result*=base;
        }
        result*=result;
        if((exponent&0x1)==1){
            result*=base;
        }
        return result;
    }

    @Test
    public void test1(){
        double result1=Power(0,0 );
        System.out.println(result1);
    }

    @Test
    public void test2(){
        double result2=Power(1,2 );
        System.out.println(result2);
    }

    @Test
    public void test3(){
        double result3=Power(2,4 );
        System.out.println(result3);
    }

    @Test
    public void test4(){
        double result4=Power(2,-2);
        System.out.println(result4);
    }
}


参考博客:https://blog.csdn.net/qq_41573234/article/details/98945725

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值