15.x的平方根

题目内容:

Leetcode-x的平方根

 

 

代码及思路:

class Solution {
public:
    int mySqrt(int x) {
        //利用二分法,1)若中间数值的平方,大于输入值,则在0-中间值当中继续迭代;
        //2)若中间数值的平方,小于输入值,则在中间值-target中继续迭代    
    if(x==0||x==1)
        return x;
    int left = 0;
	int right = x;
	int res;
	while(left<=right)
	{
		int mid = left + ( right-left) / 2;
		if (mid <= x/mid) //一定要写除法否则会溢出
		{
			left = mid + 1;
			res = mid;
		}
		else
			right = mid - 1;
	}
        return res;
 }
};

 

相关文章: