面試題16 數值的整數次方

2021-08-20 22:20:10 字數 1450 閱讀 7763

實現函式double power(double base, int exponent),求base的exponent次方。不得使用庫函式,同時不需要考慮大數問題。

分析:由於不需要考慮大數問題,這道題看起來很簡單。但是需要特別注意的是:如果輸入的指數小於1(0和負數)的時候怎麼辦?當底數是0且指數是負數的時候怎麼處理?

2.1 方法一:不夠高效的解法

#include #include #include using namespace std;

bool g_invalidinput = false;

bool equal(double num1, double num2);

double powerwithunsignedexponent(double base, unsigned int exponent);

double power(double base, int exponent)

unsigned int ab***ponent = (unsigned int)(exponent);

if (exponent < 0)

ab***ponent = (unsigned int)(-exponent);

double result = powerwithunsignedexponent(base, ab***ponent);

if (exponent < 0)

result = 1.0 / result;

return result;

}double powerwithunsignedexponent(double base, unsigned int exponent)

bool equal(double num1, double num2)

int main()

2.2 方法二:高效的解法

分析:如果輸入的指數exponent為32,則在函式的迴圈中需要做31次乘法,但我們可以換一種思路考慮:我們的目標是求乙個數字的32次方,如果我們已經知道了它的16次方,那麼只要在16次方的基礎上在平方一次就可以了,而16次方是8次方的平方,這樣類推,我們求32次方只需要做5次乘法:先求平方,在平方的基礎上求4次方,在4次方的基礎上求8次方,在8次方的基礎上求16次方,在16次方的基礎上求32次方。

也就是說,我們可以用如下公式求a的n次方:

這個公式可以在o(log n)的時間求出指數的解。

將上面的 powerwithunsignedexponent函式修改如下:

double powerwithunsignedexponent(double base, unsigned int exponent)

面試題16 數值的整數次方

題目描述 給定乙個double型別的浮點數base和int型別的整數exponent。求base的exponent次方。注意幾種特殊的輸入情況,base為0,以及exponent正負時求指數的差異。方法一 class solution else 改進版 class solution unsigned...

面試題16 數值的整數次方

一 題目 實現函式double power double base,int exponent 求base的exponent次方。不得使用庫函式,同時不需要考慮大數問題。二 關鍵 1.考慮齊全。指數是負數。底數為零且指數是負數的時候。底數是0.2.速度提高。三 解釋 1.求整數次方時,考慮如下的數學公...

面試題16 數值的整數次方

面試題16 數值的整數次方 題目 實現函式double power double base,int exponent 求base的exponent 次方。不得使用庫函式,同時不需要考慮大數問題。思路 考慮到base 0,exponent 0時,無意義。exponent 0時,結果取倒數。還有比較兩個...