题目链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/
难度:中等
描述:
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
题解
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0:
return 0
if n < 0:
x, n = 1 / x, -n
ret = 1
while n > 0:
# n为奇数
if n & 1 == 1:
ret *= x
x *= x
n >>= 1
return ret