Use Binary Search


  • 0
    S
    public boolean isPerfectSquare(int num) {
        if (num < 0) return false;
        long l = 1, r = num;
        while (l <= r) {
            long mid = l + ((r - l) >> 1);
            long re = mid * mid;
            if (re == num) return true;
            else if (re < num) l = mid + 1;
            else r = mid - 1;
        }
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.