Implement , which calculates raised to the power (i.e., x^n).
Example 1:
Example 2:
Example 3:
Problem Statement:
Given constraints ensure:
Edge Cases to Consider:
Base Cases:
Negative Exponents:
If is -1, the result should return since any number raised to the power of -1 is the reciprocal of the number.
Handling large negative values like without overflow.
If is 0, the result should return 1 since any number raised to the power of 0 is 1.
Fractional Base:
Large Positive/Negative Values of n:
Precision Issues:
Optimized Approach (Binary Exponentiation - O(log n))
Instead of multiplying by itself times (O(n) complexity), we use Exponentiation by Squaring, which reduces the complexity to .
Approach:
Time & Space Complexity Analysis:
Java Implementation: Iterative approach
public double myPow(double x, int n) {
double res = 1.0;
long exp = Math.abs((long) n);
while(exp != 0) {
if(exp % 2 == 1) {
res *= x;
exp--;
}
x *= x;
exp >>= 1; //exp / 2;
}
return (n < 0) ? 1.0 / res : res;
}
Java Implementation: Recursion Approach
Note: Recursion uses stack memory, may lead to stack overflow for large values of n.
public double myPowRecursion(double x, int n) {
if (n == 0)
return 1.0;
if (n < 0) {
return 1.0 / x * myPowRecursion(1.0 / x, -(n + 1));
}
return (n % 2 == 0) ? myPowRecursion(x * x, n / 2) : x * myPowRecursion(x * x, n / 2);
}