【演算法詳解】求解數值的整數次方

王曉斌發表於2014-03-03

1. 問題描述

實現函式:

double power(double base,int exponent)

求base的exponent次方,不使用庫函式,不考慮大數問題。


2. 解法1

考慮邊界問題;

#include <iostream>
#include <string>

using namespace std;

#define DBL_MIN 0.000001

double power(double base, int exponent)
{
    if ( base < DBL_MIN && base > -DBL_MIN)
    {
        return 0.0;
    }
    
    double result = 1.0;
    
    int unsignedExponent = exponent;
    if (exponent < 0)
    {
        unsignedExponent = -exponent;
    }
    
    for (int i = 1; i < unsignedExponent; i++)
    {
        result *= base;
    }
    
    if (exponent < 0)
    {
        result = 1.0 / result;
    }
    
    return result;
}

int main(int argc, const char * argv[])
{
    double base = 12.0;
    int exponent = -2;
    
    cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
    
    base = 0.0;
    exponent = 2;
    
    cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
    
    base = -0.000000009;
    exponent = 12;
    
    cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
    
    return 0;
}

2. 解法2

假設求解32次方,如果已知16次方,那麼只要在16次方的基礎上再平方一次就可以了,而16次方是8次方的平方,一次類推。

#include <iostream>
#include <string>

using namespace std;

#define DBL_MIN 0.000001

double powerUnsignedExponent(double base, int exponent)
{
    if (exponent == 0)
    {
        return 1.0;
    }
    
    if (exponent == 1)
    {
        return base;
    }
    
    // exponent >> 1 == exponent / 2
    double result = powerUnsignedExponent(base, exponent>>1);
    result *= result;
    
    // if exponent is odd
    if ((exponent & 0x01) == 1)
    {
        result *= base;
    }
    
    return result;
}

double power(double base, int exponent)
{
    if ( base < DBL_MIN && base > -DBL_MIN)
    {
        return 0.0;
    }
    
    double result = 1.0;
    
    int unsignedExponent = exponent;
    if (exponent < 0)
    {
        unsignedExponent = -exponent;
    }
    
    result = powerUnsignedExponent(base, unsignedExponent);
    
    if (exponent < 0)
    {
        result = 1.0 / result;
    }
    
    return result;
}

int main(int argc, const char * argv[])
{
    double base = 12.0;
    int exponent = -2;
    
    cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
    
    base = 0.0;
    exponent = 2;
    
    cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
    
    base = -0.000000009;
    exponent = 12;
    
    cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
    
    return 0;
}



參考:劍指offer 名企面試官精講典型程式設計題》 - 面試題11:數值的整數次方


相關文章