代码拉取完成,页面将自动刷新
# 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)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。