C++ 0ms solution, using binary search


  • 0
    I

    Since we know the input is an integer, the largest square root is 46340. The time complexity is O(lg(46340)). lg(46340) = 16.

    bool isPerfectSquare(int num) {
        if (num < 0) return false;
        int low = 0, high = 46340;
        while (low < high) {
            int mid = low + (high - low) / 2;
            int square = mid * mid;
            if (square < num) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low * low == num;
    }

Log in to reply
 

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