zoukankan      html  css  js  c++  java
  • 11 数的整数次方

    public class test11{
        private static boolean invalidInput = false;//指示输入是否非法
        public static double power(double base, int exponent){
            if(base>-0.0000001&&base<0.0000001){//判断是否为0
                if(exponent<0){
                    invalidInput = true;//输入非法
                }
                return 0;
            }
            if(exponent<0){
                return 1/powerWithUnsignedExponent(base,-exponent);
            }
            return powerWithUnsignedExponent2(base,exponent);
        }
        //循环
        private static double powerWithUnsignedExponent(double base, int absExponent) {
            double result = 1.0;
            for(int i=1;i<=absExponent;i++){
                result = result * base;
            }
            return result;
        }
        //递归
        private static double powerWithUnsignedExponent2(double base, int absExponent) {
            if(absExponent==0) return 1;
            if(absExponent==1) return base;
            double result = powerWithUnsignedExponent2(base,absExponent>>1);
            result *= result;
            if((absExponent&1)==1){
                result *= base;
            }
            return result;
        }
    
        public static void main(String[] args){
            System.out.println(power(2,-2));
        }
    }
  • 相关阅读:
    和为S的连续正数序列
    数组中只出现一次的数字
    平衡二叉树
    二叉树的深度
    水仙花数
    数列求和
    数值统计
    奇数乘积
    求绝对值
    求两点的距离
  • 原文地址:https://www.cnblogs.com/seven7seven/p/3930165.html
Copyright © 2011-2022 走看看