剑指Offer算法实现之十一:数值的整数次方

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

思路:
① double判零技巧
② 输入参数合法性
③ 避免重复计算,迭代公式:
剑指Offer算法实现之十一:数值的整数次方_第1张图片

编译环境:ArchLinux+Clang3.3,C++11

实现一:迭代公式+位运算

#include <iostream>
#include <stdexcept>
#include <limits>
using namespace std;

double my_power(double base, int exp)
{
    if ((base - 0.0 < numeric_limits<double>::epsilon() && 
            base - 0.0 > -numeric_limits<double>::epsilon()) &&
            exp < 0)
        throw std::invalid_argument("Invalid Params!");
    if (exp == 0)
        return 1.0;
    unsigned absExp = exp>=0 ? exp : -exp;
    unsigned mask = (1U << (sizeof(int)-1));
    while (!(mask & absExp)) {
        mask >>= 1;
    }
    double ret = base;
    mask >>= 1;
    while (mask) {
        ret *= ret;
        if (mask & absExp) {
            ret *= base;
        }
        mask >>= 1;
    }
    if (exp < 0)
        ret = 1.0 / ret;
    return ret;
}

int main()
{
    cout << my_power(2, 4) << endl;
    cout << my_power(2, -3) << endl;
    cout << my_power(0.0, 0) << endl;
    try {
        my_power(0.0, -1);
    } catch (std::invalid_argument) {
        cout << "invalid_argument caught!" << endl;
    }
}

你可能感兴趣的:(Power简单实现)