Skip to content
Bill Liao
Go back

Pow(x, n)

Edit page

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:

Approach: Binary Exponentiation (Fast Power)

Algorithm

  1. Handle the sign of n; for negative exponents, compute the positive power and take the reciprocal
  2. Use the exponent’s binary representation: repeatedly square the base and halve the exponent
  3. If the current bit of the exponent is set, multiply the result by the accumulated base
  4. Return the result

Time & Space Complexity

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:

  1. exp = 10 (binary 1010)
  2. bit 0 (0): no multiply. base = 2^2 = 4. exp = 5
  3. bit 0 (1): result = 4. base = 4^2 = 16. exp = 2
  4. bit 0 (0): no multiply. base = 256. exp = 1
  5. bit 0 (1): result = 4 * 256 = 1024. exp = 0

Answer: 1024.0.

Key Points

  1. Halving the Exponent: Each step squares the base, halving the exponent -> O(log n)
  2. Negative Exponent: Compute the positive power and return the reciprocal
  3. Integer.MIN_VALUE: Use a long before negating to avoid overflow
  4. Bit Inspection: (exp & 1) == 1 checks whether the current bit is set
  5. Edge Cases: x=0 with positive n returns 0; n=0 returns 1

Edit page
Share this post:

Previous Post
Palindrome Number
Next Post
Roman to Integer