50. Pow(x, n)

Implement pow(x, n).

public class Solution {
    public double myPow(double x, int n) {
// Need to take care of MIN_VAULE, cause -MIN > MAX
        if (n == Integer.MIN_VALUE) return x * myPow(x, n + 1);
        if (n < 0) return 1.0 / myPow(x, -n);
        if (n == 0) return 1.0;
        if (n == 1) return x;
        double temp = myPow(x, n / 2);
        if (n % 2 == 1) {
            return x * temp * temp;
        } else {
            return temp * temp;
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s