题目
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
思考
Power(a, n),如果直接计算,需要计算n-1次乘法。时间复杂度为O(n)。
考虑pow(a, n) = pow(a, n//2) * pow(a, n//2),那么只需要计算一半的乘法,因为两边一样的,只用考虑一边。(暂时忽略n奇偶)。
二分法。时间复杂度O(logn)
代码
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
return 1/self.myPow(x, abs(n))
if n == 0:
return 1
if n == 1:
return x
result = self.myPow(x, n >> 1)
result *= result
# print(result)
if (n & 1) == 1:
result *= x
return result