剑指offer 数值的整数次方

https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

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

public class Power {
    //输入错误标志
    boolean inValidInput=false;
    public double Power(double base, int exponent) {
        if(equalDouble(base,0.0)&&exponent<=0){
            inValidInput=true;
            return 0;
        }
        int exponent2=Math.abs(exponent);
        double res = getRes(base, exponent2);
        //这个慢
        //double res = getRes2(base, exponent2);
        if(exponent<0){
            res=1.0/res;
        }
        return res;
    }

    /*
    * 计算速度会变快
    * a^n=  a^(n/2)*a^(n/2)                 //n为偶数
    *       a^((n-1)/2)*a^((n-1)/2)*a   //n为寄数
    * */
    private double getRes(double base, int exponent) {
        if(exponent==0)
            return 1;
        if(exponent==1)
            return base;

        double res=getRes(base,exponent>>1);
        res*=res;
        if((exponent&1)==1){//判断exponent奇偶性
            res*=base;
        }
        return res;
    }

    //计算速度不快
    private double getRes2(double base, int exponent) {
        double res=1.0;
        for (int i=0;i

你可能感兴趣的:(数据结构,算法)