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

    本题考查库函数的实现原理,特别注意用O(logn)时间求a的n次方的优化算法。

    C++版

    #include <iostream>
    #include <cmath>
    using namespace std;
    
    bool g_InvalidInput = false;
    
    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;
    }
    
    double Power(double base, int exponent){
        g_InvalidInput = false;
        if(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;
    }
    
    int main()
    {
        cout << "Hello world!" << endl;
        cout<<Power(2,3)<<endl;
        return 0;
    }
    

      用O(logn)时间求a的n次方的优化算法。

    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;
    }
    
  • 相关阅读:
    问题总结
    Https网络安全架构设计
    分布式ID生成策略
    [转]匿名内部类详解
    JAVA名词解释
    MQ实战
    手写SpringMVC实现
    多线程问答
    BIO、NIO实战
    spring中@Value("${key}")值原样输出${key}分析与解决
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13337258.html
Copyright © 2011-2022 走看看