C++ Solution by using binary search


  • 0
    L
    
    class Solution {
    public:
        bool isPerfectSquare(int num) {
            if (num <= 0)
            {
                return false;
            }
            
            if (num == 1)
            {
                return true;
            }
            
            int low = 1;
            int high = num;
            while (low <= high)
            {
                int middle = low + (high - low) / 2;
                int reminder = num / middle;
                if (reminder == middle)
                {
                    return (num % middle == 0);
                }
                else if (reminder > middle)
                {
                    low = middle + 1;
                }
                else
                {
                    high = middle - 1;
                }
            }
            return false;
        }
    };
    

Log in to reply
 

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