Pow(x,n) Problem
Description
LeetCode Problem 50.
Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints:
- -100.0 < x < 100.0
- -2^31 <= n <= 2^31-1
- -10^4 <= x^n <= 10^4
Solution
Approach: Fast Power (Binary Exponentiation)
Multiplying x by itself n times takes O(n) steps, which is far too slow when n is around 231. Instead, use the binary digits of n.
Every exponent is a sum of powers of two, for example 13 = 8 + 4 + 1, so x13 = x8 · x4 · x1. Squaring gives the factors x, x^2, x^4, x^8, ... one after another, and we multiply into the result exactly the ones whose bit is set in n:
- If
nis negative, use x-k = (1/x)k: replacexwith1 / xand the exponent with-n. - Start with
result = 1. While the exponent is positive:- if it is odd (its lowest bit is 1), multiply
resultby the currentx; - square
xand halve the exponent (drop its lowest bit).
- if it is odd (its lowest bit is 1), multiply
Example x = 2, n = 10 (binary 1010): the loop sees bits 0, 1, 0, 1 while x is 2, 4, 16, 256, so result = 4 · 256 = 1024.
The detail people get wrong is the sign flip when n = -2^31: -n does not fit in a 32-bit integer. Store the exponent in a 64-bit variable (long in Java, long long in C++) before negating it. In JavaScript, halve with Math.floor(power / 2), because the bit shift >> works on 32-bit integers and breaks for 231.
Complexity: O(log |n|) time and O(1) extra space.
class Solution:
def myPow(self, x: float, n: int) -> float:
power = n
if power < 0: # x^(-k) = (1/x)^k
x = 1 / x
power = -power
result = 1.0
while power > 0:
if power % 2 == 1: # this bit of the exponent is set: multiply in the current x
result *= x
x *= x # x, x^2, x^4, x^8, ...
power //= 2
return result
Now write it from memory
Close the write-up and solve it yourself against the tests.