Leetcode 50. Pow(x, n)(Python3)
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
- -100.0 < x < 100.0
- n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
思路:
1.暴力 Time:O(n)
2.分治递归思想 Time:O(logn)
先介绍下递归和分治的代码框架:因为这是本道题的核心思想
递归框架:
分治框架:
2.的递归写法:
#递归法
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if not n:return 1
if n < 0:return 1 / self.myPow(x,-n)
if n % 2:return x * self.myPow(x,n-1)
return self.myPow(x*x,n//2)
递归:
1.中止条件:当n == 0:return1
2.当前层的逻辑处理:当n < 0 或者 当 n 为奇数时
3.生成结果并进入下一层
2.的递归改循环写法:
#递归改循环:
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0:
x = 1 / x
n = -n
pow = 1
while n:
if n & 1:
pow *= x
x *= x
n >>= 1
return pow
关于其中的按位运算符:http://www.runoob.com/python3/python3-basic-operators.html#ysf5
使用按位运算更高效
PS:老师说面试官更喜欢最后一种写法