367. 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
Returns: True
Example 2:

Input: 14
Returns: False

Binary search

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

        return false;
    }
}
public class Solution {
    public boolean isPerfectSquare(int num) {
        int l = 1;
        int r = num;
        while(l <= r){
            int mid = l + (r-l)/2;
            if( mid < num/mid){
                l = mid +1;
            }else if( mid == num/mid && num%mid == 0){
                return true;
            }else{
                r = mid -1;
            }
        }

        return false;
    }
}

results matching ""

    No results matching ""