Pow(x, n)(recursive, iterative)
Implementpow(x,n), which calculates x_raised to the power_n(xn).
Example 1:
Input:
2.00000, 10
Output:
1024.00000Example 2:
Input:
2.10000, 3
Output:
9.26100Example 3:
Input:
2.00000, -2
Output:
0.25000
Explanation:
2
-2
= 1/2
2
= 1/4 = 0.25分析
iterative
N = 9 = 2^3 + 2^0 = 1001 in binary. Then:
x^9 = x^(2^3) * x^(2^0)
We can see that every time we encounter a 1 in the binary representation of N, we need to multiply the answer with x^(2^i) whereiis theithbit of the exponent. Thus, we can keep a running total of repeatedly squaring x - (x, x^2, x^4, x^8, etc) and multiply it by the answer when we see a 1.
recursive
PreviousRange Minimum Query (Square Root Decomposition and Sparse Table)NextRange Sum Query 2D - Immutable(matrix)
Last updated
Was this helpful?