Valid Perfect Square

Problem: Valid Perfect Square

To check whether Y is a valid perfect square, we can use binary search to find a number X that X ^ 2 = Y.

Code in Python:

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num == 1: return True

        l, r = 0, num/2
        while l < r:
            if l == r - 1 and l * l < num and r * r > num: return False
            c = (l + r + 1) / 2
            if c * c > num: r = c
            elif c * c < num: l = c
            else: return True
        return False

results matching ""

    No results matching ""