50. Pow(x, n)
Summary
Calculate x^n without using built-in operators such as x ** n in Python.
Approach
Convert n to binary. For each bit from right to left, calculate the corresponding power of x.
- the first bit:
x - the second bit:
x^2 - the third bit:
(x^2)^2 - ...
If the bit at the i-th step is 1, multiply the current power into the answer.
Function
Initialization:
flag = -1ifn < 0, otherwise1n = abs(n)pow = xans = 1
While n > 0:
- extract the lowest bit with
n & 1 - if the lowest bit is
1, doans *= pow - square the current power with
pow *= pow - right shift
nwithn >>= 1
Complexity
Time complexity: O(log N), because we process one bit of n at a time.
Space complexity: O(1).