Leetcode JAVA刷刷站(69)x的平方根

时间:2025-04-07 17:07:53
  • public class Solution {
  • public int mySqrt(int x) {
  • if (x == 0) {
  • return 0;
  • }
  • long left = 1, right = x; // 使用long类型避免平方时溢出
  • while (left <= right) {
  • long mid = left + (right - left) / 2; // 防止溢出
  • long square = mid * mid;
  • if (square == x) {
  • return (int) mid;
  • } else if (square < x) {
  • left = mid + 1;
  • } else {
  • right = mid - 1;
  • }
  • }
  • // 当left > right时,循环结束,right为最接近x的平方根的整数(向下取整)
  • return (int) right;
  • }
  • public static void main(String[] args) {
  • Solution solution = new Solution();
  • int x = 9;
  • ("The square root of " + x + " is " + (x));
  • x = 8;
  • ("The square root of " + x + " is " + (x));
  • }
  • }