11. 数值的整数次方

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

  思路
                       {a^(n/2) * a^(n/2)                  n为偶数
            a^n = {
                       {a^(n-1)/2 * a^(n-1)/2 * a      n为奇数
  
  先取a的绝对值,然后进行后续运算,当算完之后再进行判断是否为整数,若不是取倒数。
 
  时间复杂度:O(logn)

  
  测试用例:把底数和指数分别设为正数、负数和0。

#include<iostream>
#include<math.h>
#include<cstdlib>
using namespace std;

//判断小数是否相逢时,不能直接用==,需重新写一个equal方法,让它们的差处于一个小区间
bool equal(double num1, double num2)
{
    if ((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001))
    {
        return true;
    }
    else
    {
        return false;
    }
}

double PowerWithUnsignedExponent(double base, int exponent)
{
    if (equal(base, 0.0) && exponent < 0)
    {
        return 0;
    }
    
    int absExponent = abs(exponent);

    if (absExponent == 0)
    {
        return 1;
    }

    if (absExponent == 1)
    {
        return base;
    }

    double result = PowerWithUnsignedExponent(base, absExponent >> 1);
    result *= result;

    if (absExponent & 0x1 == 1)  //奇数的话需要再乘以base
    {
        result *= base;
    }

    if (exponent < 0)
    {
        result = 1 / result;
    }

    return result;
}

void test1()
{
    cout << PowerWithUnsignedExponent(10, 4) << endl;
}

void test2()
{
    cout << PowerWithUnsignedExponent(10, -4) << endl;
}

void test3()
{
    cout << PowerWithUnsignedExponent(0, 1) << endl;
}

void test4()
{
    cout << PowerWithUnsignedExponent(0, 0) << endl;
}

int main()
{
    test1();
    test2();
    test3();
    test4();

    return 0;
}

猜你喜欢

转载自my.oschina.net/134596/blog/1795086