M O 16 數值的整數次方

2021-10-13 15:27:18 字數 1389 閱讀 7060

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

輸入:

2.00000,10

輸出:1024.00000

輸入:

2.00000,-

2輸出:

0.25000

解釋:2-2

=1/22

=1/4

=0.25

首先分三種情況:

(1)x=0時返回0

(2)當 n < 0時:把問題轉化至 n≥0 的範圍內,即執行 x = 1/x,n = - n ;

(3)當n>0時,分奇偶兩種情況

參考大神解析:link

快速冪實際上是二分思想的一種應用。

將n//2和判斷奇偶的n%2轉化為位運算:

向下整除n // 2等價於 右移一位n >> 1(python裡寫n >>=1)可以理解為二進位制每次去掉最後一位

取餘數n % 2等價於 判斷二進位制最右一位值n&1

class

solution

:def

mypow

(self, x:

float

, n:

int)

->

float

:if x==0:

return

0 res=

1if n<0:

x,n=

1/x,

-n while

(n):

if n&1:

res*=x

x*=x

n>>=1

return res

時間複雜度o(log_2 n): 二分的時間複雜度為對數級別。

空間複雜度o(1): res等變數占用常數大小額外空間。

------x&1和x>>=1位運算和快速冪要記清楚!-------2021-01-01----------

16 數值的整數次方

實現函式pow double base,int exponent 常規的思路是,迴圈相乘,雖然簡單,也有幾個要注意的地方 0 的負數次方是錯誤的輸入引數,因為負數次冪是借助除法算出,0 不能作為分母 非0數的負數次冪是,先求正數次冪,再取倒數。0 的 0 次方是無意義的 處理 or 不處理 而迴圈相...

16 數值的整數次方

public class doublepower 沒有考慮指數為負數和指數小於1的情況 param base 底數 param exponent 指數 return 結果 public static double power1 double base,int exponent return resu...

數值整數次方

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