标签:技术 方法 etc nta tps 函数 通过 位运算 ade
@
不是常规意义上的暴力,过程中通过动态调整底数的大小来加快求解。代码如下:
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
如果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
标签:技术 方法 etc nta tps 函数 通过 位运算 ade
原文地址:https://www.cnblogs.com/nangec/p/12864416.html