题目
Implement pow(x, n), which calculates x raised to the power n (x^n).
解题思路
将n转换成2进制,就可以将x的n次方,转换成若干个x的2的幂的乘积,对于这些幂,可以用前一个的平方求得
代码
class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n < 0:
            x = 1 / x
            n = -n
        res = 1
        while n > 0:
            if n % 2:
                res *= x
            n //= 2
            x *= x
        return res