zoukankan      html  css  js  c++  java
  • 面试题11:数值的整数次方

    题目描述

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

    题目分析

    剑指Offer(纪念版)P90

    代码实现

    bool g_InvalidInput = false;
    
    double Power(double base, int exponent)
    {
        g_InvalidInput = false;
     
        if(equal(base, 0.0) && exponent < 0)
        {
            g_InvalidInput = true;
            return 0.0;
        }
     
        unsigned int absExponent = (unsigned int)(exponent);
        if(exponent < 0)
            absExponent = (unsigned int)(-exponent);
     
        double result = PowerWithUnsignedExponent(base, absExponent);
        if(exponent < 0)
            result = 1.0 / result;
     
        return result;
    }
     
    /* 不够高效
    double PowerWithUnsignedExponent(double base, unsigned int exponent)
    {
        double result = 1.0;
        for(int i = 1; i <= exponent; ++i)
            result *= base;
     
        return result;
    }
    */
    double PowerWithUnsignedExponent(double base, unsigned int exponent)
    {
        if(exponent == 0)
            return 1;
        if(exponent == 1)
            return base;
    
        double result = PowerWithUnsignedExponent(base, exponent >> 1);
        result *= result;
        if((exponent & 0x1) == 1)
            result *= base;
    
        return result;
    }
    
    bool equal(double num1, double num2)
    {
        if((num1 - num2 > -0.0000001)
            && (num1 - num2 < 0.0000001))
            return true;
        else
            return false;
    }
    

      

  • 相关阅读:
    基于jenkins+gitlab的自动集成环境的搭建
    函数指针与委托
    详解C#break ,continue, return (转)
    REST 与 web service 的比较
    Python
    python
    python
    python
    python 1.0
    python 0.0
  • 原文地址:https://www.cnblogs.com/xwz0528/p/4831321.html
Copyright © 2011-2022 走看看