Implement int sqrt(int x). Compute and return the square root of x. Have you been asked this question in an interview? 用binary search,有2点需要注意: 1 结果不为整数则返回比square root 小的第一个整数,所以在二叉树的解法上要稍微做一点调整 2 变量要用long 类型,因为涉及到 平方, 所以如果mid*mid < x, mid 有可能也是结果 public class Solution { public int sqrt(int x) { long start = 0; long end = x; while (end > start + 1) { long mid = start + (end - start) / 2; if (mid * mid > x) { end = mid - 1; } else if (mid * mid < x) { start = mid;//注意不是 mid+1 } else { return (int)mid; } } if (end*end <= x) { return (int)end; } return (int)start; } }