Implement pow(x, n), which calculates x raised to the power n (i.e.,
x
n
x^n
xn).
Input: x = 2.00000, n = 10
Output: 1024.00000
Input: x = 2.10000, n = 3
Output: 9.26100
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2 − 2 = 1 / 2 2 = 1 / 4 = 0.25 2^{-2} = 1/2^2 = 1/4 = 0.25 2−2=1/22=1/4=0.25
From: LeetCode
Link: 50. Pow(x, n)
double myPow(double x, int n) {
// Helper function to calculate power for non-negative exponent
double powHelper(double x, unsigned int n) {
if (n == 0) return 1;
double half = powHelper(x, n / 2);
if (n % 2 == 0)
return half * half;
else
return half * half * x;
}
// Handling the case when n is negative
bool isNegative = false;
unsigned int positiveN = n;
if (n < 0) {
isNegative = true;
positiveN = -((unsigned int)n); // Convert to positive, handle overflow
}
double result = powHelper(x, positiveN);
// If n is negative, return the reciprocal
return isNegative ? 1 / result : result;
}