[LeetCode-69] Sqrt(x)(求解平方根)

Implement int sqrt(int x).

Compute and return the square root of x.

这道题一看到函数的定义int sqrt(int x)都是int就高兴了,直接二分吧。但是要注意,即使用long long都越界,还要用unsigned long long。最后返回值还要再检查一下。

http://blog.csdn.net/doc_sgl/article/details/12404971

int mySqrt(int x) 
{
	// Start typing your C/C++ solution below
	// DO NOT write int main() function
	
	unsigned long long begin = 0;
	unsigned long long end = (x+1)/2;
	unsigned long long mid;
	unsigned long long tmp;
	
	while(begin < end) {
		mid = begin + (end-begin)/2;
		tmp = mid*mid;
		if(tmp==x)
			return mid;
		else if(tmp<x) 
			begin = mid+1;
		else 
			end = mid-1;
	}
	
	tmp = end*end;
	
	if(tmp > x)
		return end-1;
	else
		return end;

}


如果是double 或者 float 类型时

需要使用---->牛顿迭代法

你可能感兴趣的:(LeetCode)