Posted onEdited onInLeetCodeDisqus: Symbols count in article: 1.2kReading time ≈1 mins.
O(logn) 循环版本
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defmyPow(self, x: float, n: int) -> float: if n < 0: x = 1 / x n = -n res = 1 while n: if n & 1: res *= x x *= x n >>= 1 return res
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: doublemyPow(double x, int n){ long t = labs(n); // 注意n溢出!! x = n < 0 ? 1 / x : x; double res = 1.0; while (t > 0) { if (t & 1) { res *= x; } x *= x; t >>= 1; } return res; } };
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 (n < 0) { x = 1 / x; n = -n; }
double res = 1; while (n != 0) { if (n & 1) { res *= x; } x *= x; n /= 2; // 这里一定不要用 n >>= 1因为n可能为INT_MIN } return res; } };