Pow(x, n), Leetcode 解题笔记

Implement pow(x, n).

直接for循环做也没什么问题,不过复杂度是O(n),更快的办法可以看看有没有O(log n)的呢?二分法!

public double power(double x, int n) {
	if (n == 0)
		return 1;
 
	double v = power(x, n / 2);
 
	if (n % 2 == 0) {
		return v * v;
	} else {
		return v * v * x;
	}
}
 
public double pow(double x, int n) {
	if (n < 0) {
		return 1 / power(x, -n);
	} else {
		return power(x, n);
	}
}
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