Leetcode

Sqrt(x)

  • Time:O(\log x)
  • Space:O(1)

C++

class Solution {
 public:
  int mySqrt(int x) {
    unsigned l = 1;
    unsigned r = x + 1u;

    while (l < r) {
      const unsigned m = (l + r) / 2;
      if (m > x / m)
        r = m;
      else
        l = m + 1;
    }

    // l: smallest number s.t. l * l > x
    return l - 1;
  }
};

JAVA

class Solution {
  public int mySqrt(long x) {
    long l = 1;
    long r = x + 1;

    while (l < r) {
      final long m = (l + r) / 2;
      if (m > x / m)
        r = m;
      else
        l = m + 1;
    }

    // l: smallest number s.t. l * l > x
    return (int) l - 1;
  }
}

Python

class Solution:
  def mySqrt(self, x: int) -> int:
    l = 1
    r = x + 1

    while l < r:
      m = (l + r) // 2
      if m * m > x:
        r = m
      else:
        l = m + 1

    # l: smallest number s.t. l * l > x
    return l - 1