一个数number的n次幂 python的pow函数
@
目录
实现 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
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30
三石 2020-10-29
chaochao 2020-10-27
PythonMaker 2020-10-27