My easy to understand C++ O(log n ) solution using binary search


  • 0
    M
    class Solution {
    public:
    bool isPerfectSquare(int num) {
        long low = 1;
        long high = num;
        while (low <= high) 
        {
            long mid = low + (high-low)/2 ;
            long square = mid * mid;
            if(square == num)
                return true;
            else if (square > num) 
                high = mid - 1;
            else
                low = mid + 1;
        }
        return false;
    }
    };

Log in to reply
 

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