Pow(x, n)
MediumNeetCode 150Top Interview 150 Math & GeometryWixMetaeBayProblem
Compute x raised to the power n, where x is a decimal number and
n is an integer that may be negative.
Multiplying x by itself n times is too slow for huge n, so find a faster way.
Constraints
- −100.0 < x < 100.0
- −2³¹ ≤ n ≤ 2³¹ − 1
- Either x is not 0, or n is greater than 0
- The answer fits in a double and is between −10⁴ and 10⁴
Examples: pick one to animate
Solutions
TimeO(log n)
SpaceO(1)
Time: The exponent is halved every round, so there are about log2(|n|) rounds.
Space: Only x, e and result are stored.
Write the exponent in binary. Keep squaring x (so it stands for x, x², x⁴, x⁸ …) and multiply
it into result whenever the current bit of the exponent is 1. For a negative exponent, invert x
first. Use a 64-bit exponent so negating −2³¹ cannot overflow.