Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10 Output: 1024.00000
Example 2:
Input: 2.10000, 3 Output: 9.26100
Example 3:
Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25
完成一个pow()的功能。
首先就是指数n为负的时候,只需要把x变为倒数计算即可。
指数变为正数后,一直相乘就可以了。
为了加快计算速度,指数n%2不等于0的时候可以直接按平方计算,节省时间。
这个题没有涉及到指数非负,所以相对比较简单。
class Solution:
def myPow(self, x: float, n: int) -> float:
if n<0:
x=1/x
n=-n
res=1
while n:
if n%2:
res*=x
x*=x
n//=2
return res

本文介绍了一种快速计算x^n的方法,通过将指数n转换为正数并利用平方运算来加速计算过程。当n为负数时,可以通过取x的倒数进行转换。文章提供了一个Python类实现,包括处理不同情况的详细步骤。
590

被折叠的 条评论
为什么被折叠?



