实现 pow(x, n)
,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
xxxxxxxxxx
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/powx-n
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分治法:http://timd.cn/sort/merge-sort/
递归:
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
is_positive = n > 0
n = abs(n)
res = self.my_pow(x, n)
if is_positive:
return res
return 1.0 / res
def my_pow(self, x, n):
if n == 0:
return 1
if n == 1:
return x
if n % 2 == 0:
res = self.my_pow(x, n / 2)
res = res * res
return res
else:
res = self.my_pow(x, (n - 1) / 2)
res = res * res * x
return res
迭代:
xxxxxxxxxx
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1.0
is_positive = n > 0
if not is_positive:
n = -1 * n
res = 1.0
while n > 1:
if n % 2 == 1:
res = res * x
x = x * x
n = n / 2
res = res * x
return res if is_positive else (1 / res)