Pow(x, n) - Problem
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
You need to handle both positive and negative exponents efficiently.
Note: Your solution should be more efficient than the naive approach of multiplying x by itself n times.
Input & Output
Example 1 — Positive Exponent
$
Input:
x = 2.0, n = 10
›
Output:
1024.0
💡 Note:
2^10 = 1024. Using binary exponentiation: 2^10 = (2^5)^2 = 32^2 = 1024
Example 2 — Negative Exponent
$
Input:
x = 2.1, n = -2
›
Output:
0.22676
💡 Note:
2.1^(-2) = 1/(2.1^2) = 1/4.41 ≈ 0.22676
Example 3 — Zero Exponent
$
Input:
x = 2.0, n = 0
›
Output:
1.0
💡 Note:
Any number raised to power 0 equals 1
Constraints
- -100.0 < x < 100.0
- -231 ≤ n ≤ 231-1
- -104 ≤ xn ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Base x and exponent n
2
Process
Use binary exponentiation instead of repeated multiplication
3
Output
x raised to the power n
Key Takeaway
🎯 Key Insight: Binary exponentiation reduces O(n) to O(log n) by repeatedly halving the exponent
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code