首页 > 代码库 > [LeetCode]Sqrt(x)

[LeetCode]Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

二分法,当无法求得准确值时,去较小值,(同时是最接近的)

public class Solution {
	public int sqrt(int x) {
	    if(x<1) return 0;
	    int left = 1;
	    int right = x;
	    int res = -1;
	    while(left<=right){
	    	int mid = (left+right)/2;
	    	int comp = x/mid;
	    	if(comp==mid) return mid;
	    	if(comp<mid){
	    		right = mid-1;
	    	}else{
	    		left = mid+1;
	    		res = mid;
	    	}
	    }
	    return res;
	}
}












[LeetCode]Sqrt(x)