leetcode 69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.



int mySqrt(int x)
{
	if (x == 0)
		return 0;
	long long int xx = x;
	long long int up = xx;
	long long int down = 0;
	while (true)
	{
		if (up*up > xx)
			up = (up+down)/2;
		else
		{
			int t = down;
 			down = up;
			up = 2 * up - t;
			if (up-down==1&&up*up>=xx||up==down)
				return up*up == x ? up : down;
		}
	}
}

accepted

类似二分查找,夹逼思想(不要想歪了)



你可能感兴趣的:(LeetCode)