题解 | #求平方根#
求平方根
https://www.nowcoder.com/practice/09fbfb16140b40499951f55113f2166c
import java.util.*; public class Solution { /** * * @param x int整型 * @return int整型 */ public int sqrt (int x) { // write code here if (x < 0) { throw new IllegalArgumentException("param must be positive"); } if (x == 0) { return 0; } long l = 1; long r = x; long mid; while (l < r) { mid = l + (r - l) / 2; if (mid * mid <= x && (mid + 1) * (mid + 1) > x) { return (int) mid; } else if (mid * mid < x) { l = mid + 1; } else { r = mid - 1; } } return (int) l; } }