數值整數次方

2021-08-27 16:54:51 字數 1202 閱讀 2737

/********************************************

題目:實現函式double power(double base, int exponent)

求base的exponent次方。不得使用庫函式,同時不需要考慮

大數問題。

********************************************/

#includebool equal(double num1, double num2);

double powerwithunsignedexponent(double base, unsigned int ab***ponent);

double power(double base, int exponent)

/*時間複雜度為o(n)

double powerwithunsignedexponent(double base, unsigned int ab***ponent)

*///判斷兩個double是否相等

bool equal(double num1, double num2)

//上面注釋的powerwithunsignedexponent()方法雖然能滿足功能,

//但是不夠高效時間複雜度為o(n)

//以下方法利用

//a^n = a^(n/2) * a^(n/2);當n為偶數

//a^n = a^((n-1)/2) * a^((n-1)/2) * a;當n為奇數

//其時間複雜度為o(nlogn)

double powerwithunsignedexponent(double base, unsigned int ab***ponent)

int main()

{ double result1 = power(2,4); //基數和指數都為正式

double result2 = power(2,0); //指數為0

double result3 = power(-2,1); //指數為1

double result4 = power(-3,-2); //指數為負數

std::cout << result1 //判斷兩個小數是否相等。如果兩個小數的差的絕對值很小,比如小於0,.0000001

//就可以認為他們相等。

//用位運算替換乘除法,效率高很多

==參考劍指offer

數值整數次方

題目 實現函式double power double base,int exponent 求base的exponent次方。不得使用庫函式,同時不需要考慮 大數問題。includebool equal double num1,double num2 double powerwithunsignede...

數值的整數次方

題目 實現函式double power double base,int exponent 求base的exponent次方。不得使用庫函式,同時不需要考慮大樹問題。這道題目有以下幾點需要注意 0的0次方是無意義的,非法輸入 0的負數次方相當於0作為除數,也是無意義的,非法輸入 base如果非0,如果...

數值的整數次方

在寫這個問題時,先說一下對於我們寫程式時,應該考慮的問題。的規範程度 的書寫規範程度會影響面試考官閱讀 的興致,從下圖可看出,書寫 布局和命名規則都決定著 的規範性。首先,規範的 書寫清晰。絕大部分面試都要求應聘者在白紙或者白板上書寫。不要因為擔心沒時間寫 就在紙上寫潦草或者簡略。通常面試 量不會超...