Pow(x, n) requires calculating x raised to the power n efficiently.

Problem

Implement pow(x, n), which calculates xn. The value of n can be negative, so for a negative exponent, the result is calculated as 1 / x-n.

Example(s)

Example 1

Input
x = 2.00000
n = 10
Output
1024.00000

Example 2

Input
x = 2.10000
n = 3
Output
9.26100

Solution

This problem uses Binary Exponentiation. Instead of multiplying x repeatedly, square the base and halve the exponent at every step. When the exponent is odd, multiply the result by the current base.

A long is used for the exponent because Integer.MIN_VALUE cannot be safely negated as an int.
class Solution {
    public double myPow(double x, int n) {
        long exponent = n;

        if (exponent < 0) {
            x = 1 / x;
            exponent = -exponent;
        }

        double result = 1.0;

        while (exponent > 0) {
            if (exponent % 2 == 1) {
                result *= x;
            }
            x *= x;
            exponent /= 2;
        }
        return result;
    }
}

Complexity

The time complexity is O(log n) because the exponent is divided by 2 in every iteration. The space complexity is O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion