LeetCode Solutions : Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

Java Solutions:

public class Solution {
    public int sqrt(int x) {
        if(x<0)
			return -1;
		long high=x/2+1;
		long low=0;
		while(low<=high){
			long mid=low+(high-low)/2;
			long sqr=mid*mid;
			if(sqr==(long)x)
				return (int)mid;
			else if(sqr<(long)x)
				low=mid+1;
			else
				high=mid-1;
		}
		return (int)high;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章