Valid Perfect Square

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
 class Solution {
    public boolean isPerfectSquare(int num) {
       for (long i = 1; i * i <= num; i++) {
  
            if ((i)*(i) == num) {
                return true;
            }
        }
        return false;
       
    }
}


Here, they mentioned in problem not to use in-build methods. We are going to use basic idea to solve this problem. We are going to loop i from 1 to num. If i*i == num return true, else iterate till the full loop.
Below the points to be noted:
Variable used for iterating for loop must be of type long , because if to avoid overflow in int type. Also no need to iterate till num and a condition should be i*i<=num [i.e., if i*i is greater than num no need of checking for perfect square and we can exit from loop]

Related Posts:

Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation


Please let us know your views in comment section

Subscribe us to receive updates instantly..

Happy Coding..!!

Comments

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Sequential Digits