求一个数值的整数次方,不考虑大数的问题

来源:互联网 发布:网络合同 编辑:程序博客网 时间:2024/04/29 21:41

public static double Power(double base , int exponent) 


具体实现请参考一下代码:
package cn.gt.algori;/** * 数值的整数次方  不考虑大数的问题 * @author gengtao * */public class train0808_1 {private static boolean invalidInput = false;public static void main(String[] args) {// TODO Auto-generated method stub        double number = 2.5;        int exponent = 5;        double result = Power(number , exponent);        if(invalidInput == true){        System.out.println("Invalid input!");        }        System.out.println(result);}//判断两个double数据是否相等    public static boolean equal(double num1 , double num2){    if((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001)){    return true;    }else{    return false;    }    }         public static double Power(double base , int exponent){    if(equal(base , 0.0) && exponent < 0){    invalidInput = true;    return 0.0;    }    int absExponent = exponent;    if(exponent < 0){    absExponent = -exponent;    }    double result = PowWithExponent(base , absExponent);    if(exponent < 0){    result = 1.0 / result;    }    return result;    }    //使用递归求解  用右移代替除运算,和1取与代替求余运算。    public static double PowWithExponent(double base , int absExponent){    if(absExponent == 0) return 1.0;    if(absExponent == 1) return base;    double result = PowWithExponent(base , absExponent >> 1);    result *= result;    if((absExponent & 1) == 1){    result *= base;    }    return result;    }}


0 0
原创粉丝点击