Skip to content

Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n.

You need to solve this problem efficiently.

InputOutputExplanation
Example 1Result 1Explanation for example 1
Example 2Result 2Explanation for example 2
  • Constraint 1 for Pow(x, n)
  • Constraint 2
  • Constraint 3
ApproachTimeSpaceBest When
Fast ExponentiationO(n)O(1)When applicable
IterativeO(n)O(1)When applicable
RecursiveO(n)O(1)When applicable
★ Recommended

This approach provides an efficient solution for pow(x, n).

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
powx_n_fast_exponentiation.py
def powx_n_fast_exponentiation(x: float, n: int) -> float:
"""Calculate x^n using fast exponentiation."""
if n == 0:
return 1.0
if n < 0:
x = 1 / x
n = -n
result = 1.0
while n > 0:
if n % 2 == 1:
result *= x
x *= x
n //= 2
return result
# Test cases
print(powx_n_fast_exponentiation(2.0, 10)) # 1024.0
print(powx_n_fast_exponentiation(2.1, 3)) # 9.261
🎯 Interview Favourite

This approach provides an efficient solution for pow(x, n).

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
powx_n_iterative.py
# Python Solution
# Problem: powx-n
# Approach: iterative
# Implementation placeholder for powx_n_iterative
# This file is auto-generated and should contain the solution code.
def powx_n_iterative():
pass
if __name__ == "__main__":
pass
✓ Simple

This approach provides an efficient solution for pow(x, n).

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
powx_n_recursive.py
# Python Solution
# Problem: powx-n
# Approach: recursive
# Implementation placeholder for powx_n_recursive
# This file is auto-generated and should contain the solution code.
def powx_n_recursive():
pass
if __name__ == "__main__":
pass