LeetCode | Sqrt (x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
//tag提示用binary search。要求的返回结果是int,不是实际的平方跟,用二分法找到最合适的int就行 public class Solution { public int mySqrt(int x) { if(x <= 1){ return x; } int result = 0; int left = 1; int right = x - 1; //在[1~x-1]范围内用二分找结果 while(left <= right){ //判断时不要用middle*middle == x, int middle = (left + right) / 2; //当middle比较大时,middle*middle可能会溢出越界 if(middle == x/middle){ //正巧为结果 result = middle; break; } if(middle < x/middle && (middle+1) > x/(middle+1)){ //近似为结果 result = middle; break; } if(middle < x/middle){ left = middle + 1; }else if(middle > x/middle){ right = middle - 1; } } return result; } }