Pow(x, n)(recursive, iterative)
Implementpow(x,n), which calculates x_raised to the power_n(xn).
Example 1:
Example 2:
Example 3:
分析
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