@

实现 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:根据奇偶幂分类(递归法,迭代法,位运算法)

一个数number的n次幂 python的pow函数-LMLPHP

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

python位运算符简介.

其实跟上面的方法类似,只是通过位运算符判断奇偶性并且进行除以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
05-11 22:50