moonlightshadow123
4/10/2017 - 2:59 PM

367-Valid-Perfect-Square https://leetcode.com/problems/valid-perfect-square/

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        low = 0
        high = num
        while high > low:
            mid = (high + low) / 2
            if mid * mid < num:
                low = mid + 1
            elif mid * mid > num:
                high = mid -1
            else:
                return True
        return low * low == num

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False