我们依次得到对应的 ,然后当 对应 的二进制数位是 时 。 在循环的过程中,我们通过 n & 1来判断 对应 的二进制数位, n >>= 1, x = x * x 对应着下次循环中的 和 。
当 小于 时, 我们令 , . 代码如下
Python
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defmyPow(self, x: float, n: int) -> float: if x == 0: return0 if n == 0: return1 if n < 0: n = -n x = 1/x ans = 1 while n > 0: if n & 1 == 1: ans *= x x *= x n >>= 1 return ans
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: doublemyPow(double x, int n){ if (x==0) return0; if (n==0) return1; long pow = n; if (pow < 0){ x = 1/x; pow = -pow; } double ans = 1; while (pow > 0){ if (pow&1 == 1) ans *= x; x *= x; pow >>= 1; } return ans; } };