@
實現 pow(x, n),即計算 x 的 n 次冪函式。其中n為整數。
連結: pow函式的實現——leetcode.
解法1:暴力法
不是常規意義上的暴力,過程中通過動態調整底數的大小來加快求解。程式碼如下:
def my_pow(number, n):
judge = True
if n < 0:
n = -n
judge = False
if n == 0:
return 1
result = 1
count = 1
temp = number
while n > 0:
if n >= count:
result *= temp
temp = temp * number
n -= count
count += 1
else:
temp /= number
count -= 1
return result if judge else 1/judge
解法2:根據奇偶冪分類(遞迴法,迭代法,位運演算法)
如果n為偶數,則pow(x,n) = pow(x^2, n/2);
如果n為奇數,則pow(x,n) = x*pow(x^2, (n-1)/2)。
class MyPow:
def my_pow(self, number, n):
if n < 0:
n = -n
return 1/self.help_(number, n)
return self.help_(number, n)
def help_(self, number, n):
if n == 0:
return 1
if n%2 == 0:
return self.help_(number*number, n//2)
return self.help_(number*number, (n-1)//2)*number
迭代程式碼如下:
class MyPow:
def my_pow(self, number, n):
judge = True
if n < 0:
n = -n
judge = False
result = 1
while n > 0:
if n%2 == 0:
number *= number
n //= 2
result *= number
n -= 1
return result if judge else 1/result
其實跟上面的方法類似,只是通過位運算子判斷奇偶性並且進行除以2的操作(移位操作)。程式碼如下:
class Solution:
def myPow(self, x: float, n: int) -> float:
judge = True
if n < 0:
n = -n
judge = False
final = 1
while n>0:
if n & 1: #代表是奇數
final *= x
x *= x
n >>= 1 # 右移一位
return final if judge else 1/final