题目:
Pow(x, n):实现 pow(x, n) ,即计算 x 的 n 次幂函数。
说明:
- -100.0 < x < 100.0
- n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
思路:暴力法,然后做了下改进,纯粹的暴力法会超时。
程序:
class Solution:
def myPow(self, x: float, n: int) -> float:
if abs(x) >= 100:
return 0.0
if n < (-1) * 2 ** 31 or n > 2 ** 31 - 1:
return 0.0
if x == 0:
return 0.0
if n == 0:
return 1.0
sign = 1
if n < 0:
sign = 0
n = -n
result = 1
auxiliary = x
counter = 1
while n > 0:
if n >= counter:
result = result * auxiliary
auxiliary = auxiliary * x
n = n - counter
counter += 1
else:
auxiliary = auxiliary / x
counter -= 1
if sign == 1:
return result
elif sign == 0:
return 1 / result