All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0301_0400.s0367_valid_perfect_square.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0301_0400.s0367_valid_perfect_square;

// #Easy #Math #Binary_Search #Binary_Search_I_Day_3
// #2022_07_12_Time_0_ms_(100.00%)_Space_40.9_MB_(49.73%)

/**
 * 367 - Valid Perfect Square\.
 *
 * Easy
 *
 * Given a **positive** integer _num_, write a function which returns True if _num_ is a perfect square else False.
 *
 * **Follow up:** **Do not** use any built-in library function such as `sqrt`.
 *
 * **Example 1:**
 *
 * **Input:** num = 16
 *
 * **Output:** true
 *
 * **Example 2:**
 *
 * **Input:** num = 14
 *
 * **Output:** false
 *
 * **Constraints:**
 *
 * *   `1 <= num <= 2^31 - 1`
**/
public class Solution {
    public boolean isPerfectSquare(int num) {
        if (num == 0) {
            // If num is 0 return false
            return false;
        }
        // long datatype can holds huge number.
        long start = 0;
        long end = num;
        long mid;
        while (start <= end) {
            // until start is lesser or equal to end do this
            // Finding middle value
            mid = start + (end - start) / 2;
            if (mid * mid == num) {
                // if mid*mid == num return true
                return true;
            } else if (mid * mid < num) {
                // if num is greater than mid*mid then make start = mid + 1
                start = mid + 1;
            } else if (mid * mid > num) {
                // if num is lesser than mid*mid then make end = mid - 1
                end = mid - 1;
            }
        }
        return false;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy