Perfect Square - The Coding Shala

Home >> Interview Questions >> Perfect Square

Check if a given number is perfect square or not

In this post, we will see how to check if a given number is a perfect square or not. Given a positive integer num, write a function that 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

Java Program to check a perfect square

Approach:
We can use a binary search to check if the given number is a perfect square or not instead of checking number one by one.
Java Code: 

class Solution {
    public boolean isPerfectSquare(int num) {
        if(num == 1) return true;
        int left = 1;
        int right = num/2;
        while(left < right){
            int mid = left + (right-left)/2;
            if((long)mid*mid == (long)num) return true;
            if((long)mid*mid > (long)num) right = mid-1;
            else left = mid+1;
        }
        if((long)right*right == (long)num) return true;
        return false;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala