码迷,mamicode.com
首页 > 其他好文 > 详细

面试题16:数值的整数次方

时间:2020-07-18 22:28:09      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:bool   数值的整数次方   mes   ace   double   signed   原理   with   power   

本题考查库函数的实现原理,特别注意用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;
}

面试题16:数值的整数次方

标签:bool   数值的整数次方   mes   ace   double   signed   原理   with   power   

原文地址:https://www.cnblogs.com/flyingrun/p/13337258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!