Pow(x, n)
Implement pow(x, n), which returns x raised to the power n. Don't use a built-in power function.
n can be negative, in which case x^n is 1 / x^-n. The tests round your answer to 5 decimal places before comparing.
Example 1
Input: x = 2.0, n = 10 Output: 1024.0
Example 2
Input: x = 2.0, n = -2 Output: 0.25
2^-2 is 1 / 2^2, which is 1 / 4.
Constraints
-100.0 < x < 100.0-2^31 <= n <= 2^31 - 1xisn't0whennis negative or0.- The answer is between
-10^4and10^4after rounding.
Approach
Multiplying x by itself n times is O(n), which is far too slow when n is in the billions. Squaring saves the work: x^2 gives x^4 with one multiplication, x^4 gives x^8, and so on.
Write n in binary. Each set bit says one of those squares belongs in the answer. For example, 13 is 1101 in binary, so x^13 = x^8 * x^4 * x^1. Loop over the bits of n from lowest to highest, keeping the current square of x. When the bit is 1, multiply it into the result. After each bit, square x and shift n right.
For a negative n, compute (1/x)^(-n) instead. In Java and C++, store n in a 64-bit variable first, because negating -2^31 overflows a 32-bit int.
Steps
- Copy
ninto a 64-bitpower. If it's negative, setx = 1 / xandpower = -power. - Set
result = 1. - While
power > 0, multiplyresultbyxif the lowest bit ofpoweris1. - Square
xand shiftpowerright by one bit. - Return
result.
def my_pow(x: float, n: int) -> float:
if n < 0:
x, n = 1 / x, -n # x^(-n) == (1/x)^n
result = 1.0
while n:
if n & 1:
result *= x # this bit of n contributes the current power of x
x *= x # x, x^2, x^4, x^8, ...
n >>= 1
return resultComplexity
- Time:
O(log |n|). There's one step per bit ofn. - Space:
O(1).
Common mistakes
- Negating
nin a 32-bit int.-(-2147483648)overflows back to-2147483648. - Looping
ntimes. It's correct but times out for large exponents. - Forgetting negative exponents, or handling them by computing
x^nfirst and taking1 / x^nwhenx^nhas already overflowed to infinity.