11/25/2020

[LeetCode] 367. Valid Perfect Square

 Problem : https://leetcode.com/problems/valid-perfect-square/

Generally, for number N, it's square root is in the range of [1, N)

Use binary search to find the square root.


class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        
        left, right = 1, num
        
        while left <= right:
            
            mid = left + (right - left) // 2
            
            if mid * mid == num:
                return True
            
            if mid * mid > num:
                right = mid - 1
            else:
                left = mid + 1
        
        
        return False

No comments:

Post a Comment