mediumMath & GeometryFacebookLinkedIn
Rapid Exponent
A calculator computes x^n using binary exponentiation to achieve logarithmic cost.
Implement pow(x, n), computing x raised to the power n.
Choose approach
2
010
1Mapstate
cur→2
ans→1
N→10
1/6
Narrationstep 1 of 6
Init cur=2, ans=1.
Variables
x=2
n=10
cur=2
ans=1
How to think about it
- Flip base and negate n when n < 0.
- O(log n) multiplications.
Edge cases to catch in interview
- n = 0 -> 1.
- Overflow for min int: cast to long first.
Examples
Example 1
0.25{"x":2,"n":-2,"values":[2,-2]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed