Pow(x, n)
Implement pow(x, n), which computes x raised to the power n — including negative exponents — without the built-in power operator.
Intuition
Multiplying x by itself n times is O(n). Instead, square the base and halve the exponent: x^n = (x^2)^(n/2). Each step throws away half the work, so it finishes in O(log n).
Approach
The naive loop is O(n)
Multiplying result by x exactly n times is correct but slow — for large n (up to ~2^31) that is far too many multiplications. The trick is that exponents split: x^n = (x^2)^(n//2), with one extra x left over when n is odd.
Square-and-halve (binary exponentiation)
Walk the exponent down toward zero. At each step, if the current exponent is odd, fold one factor of the current base into result. Then square the base and halve the exponent. This processes the exponent's binary representation bit by bit, so it runs in O(log n) multiplications instead of O(n).
Handle the negative power
A negative exponent just means a reciprocal: compute x^|n| with the loop above, then return 1 / result. Taking the absolute value up front keeps the loop logic identical for both signs.
Solution & live demo
Edge cases
Any base to the zero power is 1; the loop never runs and result stays 1.
Compute the positive power, then take the reciprocal 1 / result.
Still O(log n); squaring stays at 1 or alternates sign correctly.