zoukankan      html  css  js  c++  java
  • 剑指offer-数值的整数次方

    题目描述

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

    /**
         * 考虑情况: 指数可能为正,负,0.
         * 底数为0,指数为0或者负数,抛异常处理
         * @param base 底数
         * @param exponent 指数 
         * @return
         */
        public static double power(double base, int exponent) {
            // 指数和底数不能同时为0,数学上没有意义
            if(equal(base, 0.0) && exponent <= 0)
                throw new RuntimeException("Invalid Iuput. base and exponent both are zero");
            
            // 指数为0,返回1
            if(exponent == 0)
                return 1.0;
            
            int exp = exponent;
    
            if(exponent < 0)
                exp = - exp;   
            
            // 求幂次方
            double result = powerWithUnsignedExponent(base, exp);  
            
            // 指数为负,求倒数
            if(exponent < 0) {
                result = 1.0 / result;
            }
            
            return result;
            
        }
        private static double powerWithUnsignedExponent(double base, int exp) {
            double result = 1.0;
            for(int i=1; i<=exp; i++) {
                result *= base;
            }
            return result;
        }
        
        // 比较两个double型数据
        private static boolean equal(double num1, double num2) {
            if((num1 - num2 > -0.0000001) && (num1-num2 < 0.0000001)) 
                return true;
            return false;
        }

    优化方法:

    private static double powerWithUnsignedExponent1(double base, int exp) {
            if(exp == 0)
                return 1.0;
            if(exp == 1)
                return base;
            double result = powerWithUnsignedExponent(base, exp >> 1);  // 右移代替除以2
            result *= result;
            if((exp & 1) == 1) {   // 判断奇偶次幂,位于代替求余运算
                result *= base;
            }
            return result;
        }
  • 相关阅读:
    selenium之WebDriver API
    python开发之面试题
    python开发之协程
    Python爬虫
    Python基础
    Django-搭建win7虚拟环境-virtualenv
    Linux系列
    Python知识点
    Python知识点
    Python基础-生物信息:找出基因,生物学家使用字母A、C、T和G构成的字符串建模一个基因组。
  • 原文地址:https://www.cnblogs.com/zywu/p/5768050.html
Copyright © 2011-2022 走看看