‹ DS&A interview · Socratic
DSA · Math · #139

Pow(x, n)

Module 58 · difficulty 3/5·30:00starts on first keystroke

Implement `pow(x, n)`, which calculates `x` raised to the power `n` (i.e. `x^n`). Implement the function `myPow(x, n)` that takes a floating-point base `x` and an integer exponent `n` (which may be negative or zero) and returns `x^n` as a number. Do not use the built-in `Math.pow`. Aim for better than O(n) time.

Examples
  • x = 2.00000, n = 10 1024.00000
  • x = 2.10000, n = 3 9.261002.1^3 = 9.261
  • x = 2.00000, n = -2 0.250002^-2 = 1/2^2 = 1/4 = 0.25
Constraints
  • · -100.0 < x < 100.0
  • · -2^31 <= n <= 2^31 - 1
  • · n is an integer
  • · Either x is not zero or n > 0
  • · -10^4 <= x^n <= 10^4
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.