剑指offer 面试题11

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

#include<iostream>
using namespace std;

double PowerUnsigned(double base ,unsigned int exponent)
{
    if (exponent == 0)
        return 1;
    if (exponent == 1)
        return base;
    double result = PowerUnsigned(base,exponent>>1);
    result *= result;
    if ((exponent & 0x1) == 1)
        result = result*base;
    return result;

}

bool equal(double num1,double num2)
{
    if ((num1 - num2 > -0.00000001) && (num1 - num2 < 0.00000001))
        return true;
    else
        return false;
}

double Power(double base, int exponent)
{
    if (equal(base, 0) && exponent < 0)
        throw exception("Invaild value");

    unsigned int absExponent = static_cast<unsigned int>(abs(exponent));

    double result = PowerUnsigned(base, absExponent);
    if (exponent < 0)
        result = 1 / result;
    return result;

}

int main()
{

    double v1 = 2;
    int v2 = -1;
    cout<<Power(v1,v2);

    return 0;
}

你可能感兴趣的:(剑指offer 面试题11)