50. Pow(x, n)

Implement pow(x, n).

public class Solution {
public double myPow(double x, int n) {
if (n == Integer.MIN_VALUE) return myPow(x, n + 1) / x;
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;
}
}
}
[java]

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