CodeArchon

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
0
10
1
Mapstate
cur→2
ans→1
N→10
1/6
Narrationstep 1 of 6

Init cur=2, ans=1.

1def myPow(x, n):
2 def helper(x, n):
3 if n == 0: return 1
4 half = helper(x, n // 2)
5 return half * half * x if n % 2 else half * half
6 return 1 / helper(x, -n) if n < 0 else helper(x, n)
Variables
x=2
n=10
cur=2
ans=1

How to think about it

  1. Flip base and negate n when n < 0.
  2. O(log n) multiplications.

Edge cases to catch in interview

  • n = 0 -> 1.
  • Overflow for min int: cast to long first.

Examples

Example 10.25
{"x":2,"n":-2,"values":[2,-2]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed