@
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 &