1 Star 0 Fork 0

wd6/LeetCode-1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
powx-n.py 963 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 9年前 . Update powx-n.py
# Time: O(logn) = O(1)
# Space: O(1)
# Implement pow(x, n).
# Iterative solution.
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
result = 1
abs_n = abs(n)
while abs_n:
if abs_n & 1:
result *= x
abs_n >>= 1
x *= x
return 1 / result if n < 0 else result
# Time: O(logn)
# Space: O(logn)
# Recursive solution.
class Solution2(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0 and n != -n:
return 1.0 / self.myPow(x, -n)
if n == 0:
return 1
v = self.myPow(x, n / 2)
if n % 2 == 0:
return v * v
else:
return v * v * x
if __name__ == "__main__":
print Solution().pow(3, 5)
print Solution().pow(3, -5)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wd6/LeetCode-1.git
git@gitee.com:wd6/LeetCode-1.git
wd6
LeetCode-1
LeetCode-1
master

搜索帮助