首页 > 其他 > 详细

[LeetCode]Sqrt(x)

时间:2014-10-22 18:15:50      阅读:181      评论:0      收藏:0      [点我收藏+]

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)

原文:http://blog.csdn.net/guorudi/article/details/40378921

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!