classSolution { doublequickMul(double x, long n){ if (n == 0) return1.0; double y = myPow(x, n >> 1); return n & 1 ? y * y * x : y * y; } public: doublemyPow(double x, int n){ return n >= 0 ? quickMul(x, n) : 1.0 / quickMul(x, -(long)n); // -n会溢出int } };
时间复杂度:O(logn) 空间复杂度:O(logn)
快速幂:迭代
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: doublemyPow(double x, int n){ double res = 1.0; long nl = n >= 0 ? n : -(long)n; for (; nl; nl >>= 1) { if (nl & 1) res *= x; x *= x; } return n >= 0 ? res : 1.0 / res; } };