Pow(x, n)
LeetCode 50 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25
Constraints:
- `-100.0 0`.
- `-10^4 <= x^n <= 10^4`
Topics: Math, Recursion
Approachβ
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
When to use
Problems with clear mathematical structure, counting, number properties.
Solutionsβ
Solution 1: C# (Best: 48 ms)β
| Metric | Value |
|---|---|
| Runtime | 48 ms |
| Memory | 14.5 MB |
| Date | 2019-12-15 |
Solution
public class Solution {
public double MyPow(double x, int n) {
double temp = x;
if (n == 0)
return 1;
temp = MyPow(x, n / 2);
if (n % 2 == 0)
return temp * temp;
else
{
if (n > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Discuss the brute force approach first, then optimize. Explain your thought process.