50. Pow(x, n)
- Implement pow(x, n), which calculates
x
raised to the powern
(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
Method 1
【O(log(n)) time | O(1) space】
package Leetcode.MathGeometry;
/**
* Author: Xingxing Zheng
* Date: 2024/12/16
*/
public class PowXN {
public static double myPow(double x, int n) {
// Handle edge cases where the base is 0 or the exponent is 0
if (x == 0) {
return 0; // Any number raised to a power with base 0 is 0
}
if (n == 0) {
return 1; // Any number raised to the power of 0 is 1
}
// Convert n to long to handle Integer.MIN_VALUE edge case
long N = n;
if (N < 0) {
// If the exponent is negative, take the reciprocal of the base
x = 1 / x;
N = -N; // Make the exponent positive
}
// Initialize the result to 1
double result = 1.0;
// Implement fast exponentiation
while (N > 0) {
// If the current bit of N (binary representation) is 1
if (N % 2 == 1) {
result *= x; // Multiply the current base value (x) into the result
}
// Update the base value by squaring it
// This allows us to compute powers of 2 efficiently (e.g., x^2, x^4, x^8, etc.)
x *= x;
// Shift N to the right by 1 bit (equivalent to dividing by 2)
// This moves to the next higher power of 2 in the binary representation of N
N /= 2;
}
return result; // Return the final result
}
public static void main(String[] args) {
// Test cases
System.out.println("2^10 = " + myPow(2, 10)); // Output: 1024.0
System.out.println("2^-2 = " + myPow(2, -2)); // Output: 0.25
System.out.println("0^5 = " + myPow(0, 5)); // Output: 0.0
System.out.println("5^0 = " + myPow(5, 0)); // Output: 1.0
System.out.println("(-2)^3 = " + myPow(-2, 3)); // Output: -8.0
System.out.println("(-2)^-3 = " + myPow(-2, -3)); // Output: -0.125
}
}
Enjoy Reading This Article?
Here are some more articles you might like to read next: