web123456

Leetcode JAVA brushing station (69) x square root

  • public class Solution {
  • public int mySqrt(int x) {
  • if (x == 0) {
  • return 0;
  • }
  • long left = 1, right = x; // Use long type to avoid overflow when squared
  • while (left <= right) {
  • long mid = left + (right - left) / 2; // Prevent overflow
  • long square = mid * mid;
  • if (square == x) {
  • return (int) mid;
  • } else if (square < x) {
  • left = mid + 1;
  • } else {
  • right = mid - 1;
  • }
  • }
  • // When left > right, the loop ends, right is an integer closest to the square root of x (rounded down)
  • 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));
  • }
  • }