Sunday, August 21, 2016

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

Nothing special, bisection method. You can choose any initial value. I choose num / 2, but I believe there are better ways. Let me know.


    public boolean isPerfectSquare(int num) {
        if (num == 1) {
            return true;
        }
        long sqrt = num / 2;
        while (sqrt > 0 && sqrt < num) {
            long square = sqrt * sqrt;
            if (square == num) {
                return true;
            } else if (square > num) {
                sqrt /= 2;
            } else {
                if ((sqrt + 1) * (sqrt + 1) > num) {
                    return false;
                }
                sqrt++;
            }
        }
        return false;
    }

No comments:

Post a Comment