本文共 583 字,大约阅读时间需要 1 分钟。
Implement , which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10Output: 1024.00000
Example 2:
Input: 2.10000, 3Output: 9.26100
Example 3:
Input: 2.00000, -2Output: 0.25000Explanation: 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
转载地址:http://vcrbb.baihongyu.com/