快速计算次方的方法。
首先,先保证n是正数。
如果n<0,就让x取反,n取绝对值。
然后考虑怎么快速乘法。
考虑 x 7 = x 1 + 2 + 4 = x ∗ x 2 ∗ x 4 x^7=x^{1+2+4}=x*x^2*x^4 x7=x1+2+4=x∗x2∗x4,可以发现,本来乘6次x,如果x自身也在迭代取平方,则只要4次乘法。
这就好办了。
考虑n变成二进制,则就变成了1+2+4这种形式,如果有1 2 4,就乘,否则只迭代x。
class Solution:def myPow(self, x: float, n: int) -> float:if x == 0:return 0 res = 1 if n < 0:x = 1/xn = -n while n:if n%2 == 1: res *=x x *= x n >>= 1return res