367. Valid Perfect Square

Link

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
Output: true

Example 2:

Input: 14
Output: false

Solution

Binary Search

    public boolean isPerfectSquare(int num) {
        if(num == 0) return true;
        int left = 1; int right = num;
        while(right > left)
        {
            int mid = left + (right - left)/2;
            if(mid == num/mid && num%mid == 0) return true;
            else if ( mid > num/mid){
                right = mid - 1;
            }else{
                left = mid + 1;
            }
        }
        return (left == num/left && num%left == 0);
    }

Last updated

Was this helpful?