數值的整數次方

2021-10-17 21:00:42 字數 592 閱讀 8052

給定乙個double型別的浮點數base和int型別的整數exponent。求base的exponent次方。

保證base和exponent不同時為0。

時間複雜度為o(logn)。

本質上是把指數轉化為其二進位制表示進行求解。再使用乙個指標cur記錄當前位上的數。從右向左分析指數二進位製上的數字,是1代表cur的值應該累乘到結果,是0表示當前值不應該累乘到結果。

因為指數的二進位制形式最多有o(logn)位,所以時間複雜度為o(logn)。

public

class

solution

if(base ==0)

boolean negative =

false;if

(exponent <0)

double res =1;

double cur = base;

//將exponent用二進位制表示,對應是1的位就累加到結果

while

(exponent !=0)

cur = cur*cur;}if

(negative)

else

}}

數值整數次方

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

數值整數次方

題目 實現函式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,如果...