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 <=0 ) return 0; int left = 1; int right = (int)Math.ceil(((long)x+1)/2); int rst = -1; long diff = Long.MAX_VALUE; while(left <= right) { int mid = (left + right)/2; long tmp = (long)mid*mid; if(tmp == x) { return mid; } if(tmp > x) right = mid - 1; else { left = mid + 1; if(Math.abs(tmp - x) < diff){ rst = mid; diff = Math.abs(tmp - x); } } } return rst; } }
他人代码:
public class Solution { public int sqrt(int x) { if (x == 1 || x == 0) { return x; } int left = 1; int right = x; while (left < right - 1) { int mid = left + (right - left) / 2; int quo = x / mid; if (quo == mid) { return quo; // mid is too big } else if (quo < mid) { right = mid; } else { left = mid; } } return left; } }
学习之处:
原文:http://www.cnblogs.com/sunshisonghit/p/4382136.html