classSolution { public: doublemyPow(double x, int _n){ if (!x || x == 1) return x; longlong n = _n; bool is_minus = _n < 0; n = is_minus ? -n : n; // 快速幂 double res = 1; while (n) { if (n & 1) res = res * x; x *= x; n >>= 1; }
return is_minus ? 1 / res : res; } };
写法 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: doublemyPow(double x, int n){ typedeflonglong LL; double res = 1; bool is_minus = n < 0;
for (LL k = abs(LL(n)); k; k >>= 1) { if (k & 1) res *= x; x *= x; }