50. Pow(x, n)
题目描述
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
示例
输入:x = 2.00000, n = 10
输出:1024.00000
思路
来自leetcode官方思路
代码
class Solution:
def myPow(self, x: float, n: int) -> float:
def function(x, n):
res = 1
x_now = x
while n:
if n % 2 == 1:
res *= x_now
x_now *= x_now
n //= 2
return res
N = abs(n)
res = function(x, N)
if n > 0:
return res
else:
return 1 / res
效率
执行用时:
28 ms, 在所有 Python3 提交中击败了98.93%的用户
内存消耗:
14.9 MB, 在所有 Python3 提交中击败了29.71%的用户
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/powx-n
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。