LeetCode Solutions

367. Valid Perfect Square

Time: $O(\log num)$

Space: $O(1)$

			

class Solution {
 public:
  bool isPerfectSquare(int num) {
    long l = 1;
    long r = num;

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

    return l * l == num;
  }
};
			

class Solution {
  public boolean isPerfectSquare(int num) {
    long l = 1;
    long r = num;

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

    return l * l == num;
  }
}
			

class Solution:
  def isPerfectSquare(self, num: int) -> bool:
    l = 1
    r = num

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

    return l * l == num