1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public: double myPow(double x, int n) { long long N = n; bool isNegative = x < 0 && N % 2 == 1; if (isNegative) x = -x; if (N < 0) { N = -N; x = 1 / x; } double ans = 1; while (N > 0) { if (N & 1) ans *= x; x *= x; N >>= 1; }
if (isNegative) ans = -ans; return ans; } };
|