码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Sqrt(x)

时间:2014-10-22 18:17:03      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

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)

标签:java   leetcode   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!