剑指offer 16. 数值的整数次方
题目:实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。 中等
方法:快速幂 时间复杂度O(logn) 空间复杂度O(1)
def myPow(x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 if x == 0 and n < 0: return -1 if n < 0: x,n = 1/x,-n result = 1 while n: if n & 1: result = result * x n >>= 1 x = x*x return result

浙公网安备 33010602011771号