首页 > 代码库 > LeetCode:Sqrt(x)

LeetCode:Sqrt(x)

题目描述:

Implement int sqrt(int x).

Compute and return the square root of x.


思路分析:采用二分查找的思想。当未找到mid=x/mid时,若mid>x/mid,则表示mid-1为平方值最接近但不超过x的值,即结果为mid-1。若mid<x/mid,则表示结果为mid为平方值最接近但不超过x的值,即结果为mid。


代码:

     if(x == 0 || x == 1)
           return x;
        int start = 0;
     	int end = x;
    	int result;
	
    	while(start <= end)
    	{
	    	int mid = (start+end)/2;
	    	if(mid == x/mid)
	    		return mid;
	    	else if(mid > x/mid)
	    	{
	    	    end = mid - 1;
	    	    result = mid - 1;
	    	}
	    	else
	    	{
	    	    start = mid + 1;
	    	    result = mid;
	    	}
    	}
	    return result;
     }


LeetCode:Sqrt(x)