zoukankan      html  css  js  c++  java
  • 剑指Offer:面试题11——数值的整数次方(java实现)

    题目描述:

    实现函数double Power(double base, int exponent),求base的exponent次方,不得使用库函数,同时不需要考虑大数问题

    思路:本题的重点考察内容是代码的完整性,要综合考虑输入的合法性,边界值等等,同时也可以进行优化

    实现一:

    public double Power(double base, int exponent){
    
        double result = 1.0;
        for(int i = 0; i < exponent; i++){
            result *= base;
        }
        return result;
    }

    这里没有考虑任何输入的非法性以及指数的负数情况。

    实现二:

    boolean g_InvalidInput = false;
    
    public double Power(double base, int exponent){
        g_InvalidInput = false;
        if(equal(base, 0.0) && exponent < 0){
            g_InvalidInput = true;
            return 0.0;
        }
        int absExp = Math.abs(exponent);
        double result = PowerWithPositiveExp(base, absExp);
        if(exponent < 0){
            result = 1.0/result;
        }
        return result;
    }
    
    public static double PowerWithPositiveExp(double base, int exp){
        double result = 1.0;
        for(int i = 0; i < exp; i++){
            result *= base;
        }
        return result;
    }
    
    public static boolean equal(double d1, double d2){
        if((d1 - d2 > -0.0000001) && ( d1 - d2 < 0.0000001)){
            return true;
        }else{
            return false;
        }
    }

    上述程序中对输入参数进行了合法性检查,同时设计了全局变量来标记输入的合法性表示。

    但是上述代码还是不够高效。

    实现3

    public static double PowerWithPositiveExp(double base, int exp){
        if(exp == 0){
            return 1;
        }
        if(exp == 1){
            return base;
        }
    
        double result = PowerWithPositiveExp(base, exp >> 1);
        result *= result;
        if(exp & 0x1 == 1){
            resutl *= base;
        }
        return result;
    }

    这里利用了公式:

    a^n = a^(n/2)* a^(n/2)*base

    其中n为偶数时, base = 1; n为奇数时,base = a.

    另外:使用位运算提高效率
    除以2等价于 >> 1
    模 2等价于 & 0x1

  • 相关阅读:
    PointToPointNetDevice doesn't support TapBridgeHelper
    NS3系列—10———NS3 NodeContainer
    NS3系列—9———NS3 IP首部校验和
    NS3系列—8———NS3编译运行
    【习题 7-6 UVA
    【Good Bye 2017 C】 New Year and Curling
    【Good Bye 2017 B】 New Year and Buggy Bot
    【Good Bye 2017 A】New Year and Counting Cards
    【Educational Codeforces Round 35 D】Inversion Counting
    【Educational Codeforces Round 35 C】Two Cakes
  • 原文地址:https://www.cnblogs.com/wenbaoli/p/5655725.html
Copyright © 2011-2022 走看看