leetcode 二分法 Pow(x, n)

Pow(x, n)

 Total Accepted: 25273 Total Submissions: 97470My Submissions

Implement pow(xn).




题意:求x的n次幂
思路:二分法
n有可能是负的或正的
当n为负是,pow(x, n) = 1/pow(x, -n)
x^n = x^{n/2} * x^{n/2}* x^{n%2}
复杂度:时间O(log n)。空间O(1)

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;
}


double pow(double x, int n){
	if(n > 0){
		return power(x, n);
	}else{
		return 1/power(x, -n);
	}
}


posted @ 2017-07-03 08:10  cxchanpin  阅读(260)  评论(0编辑  收藏  举报