Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
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/22 = 1/4 = 0.25
Constraints:
-100.0 < x < 100.0-231 <= n <= 231-1nis an integer.- Either
xis not zero orn > 0. -104 <= xn <= 104
Approach: Binary Exponentiation (Fast Power)
Algorithm
- Handle the sign of
n; for negative exponents, compute the positive power and take the reciprocal - Use the exponent’s binary representation: repeatedly square the base and halve the exponent
- If the current bit of the exponent is set, multiply the result by the accumulated base
- Return the result
Time & Space Complexity
- Time Complexity: O(log n) - the exponent is halved each step
- Space Complexity: O(1) - iterative implementation
Java Implementation
public class Pow {
/**
* Calculate x raised to the power n.
* @param x Base
* @param n Exponent (can be negative)
* @return x^n
*/
public static double myPow(double x, int n) {
// Avoid overflow when negating Integer.MIN_VALUE
long exp = n;
boolean negative = exp < 0;
exp = Math.abs(exp);
double result = 1.0;
double base = x;
while (exp > 0) {
if ((exp & 1) == 1) {
result *= base;
}
base *= base;
exp >>= 1;
}
return negative ? 1.0 / result : result;
}
// Test method
public static void main(String[] args) {
System.out.println("Input: x = 2.0, n = 10");
System.out.println("Output: " + myPow(2.0, 10)); // Expected: 1024.0
System.out.println("Input: x = 2.1, n = 3");
System.out.println("Output: " + myPow(2.1, 3)); // Expected: 9.261
System.out.println("Input: x = 2.0, n = -2");
System.out.println("Output: " + myPow(2.0, -2)); // Expected: 0.25
}
}
Example Walkthrough
For x = 2.0, n = 10:
- exp = 10 (binary
1010) - bit 0 (0): no multiply. base = 2^2 = 4. exp = 5
- bit 0 (1): result = 4. base = 4^2 = 16. exp = 2
- bit 0 (0): no multiply. base = 256. exp = 1
- bit 0 (1): result = 4 * 256 = 1024. exp = 0
Answer: 1024.0.
Key Points
- Halving the Exponent: Each step squares the base, halving the exponent -> O(log n)
- Negative Exponent: Compute the positive power and return the reciprocal
- Integer.MIN_VALUE: Use a
longbefore negating to avoid overflow - Bit Inspection:
(exp & 1) == 1checks whether the current bit is set - Edge Cases: x=0 with positive n returns 0; n=0 returns 1