Share my C++ solution using "Binary Search",easy to understand


  • 0
    V
    class Solution {
    public:
        bool isPerfectSquare(int num) {
            if (num <= 0)
                return false;
            
            int last[] = {0, 1, 4 , 5, 6, 9};
            if (find(last, last + 6, num%10) == last+6)
                return false;
                
            int left = 0;
            int right = 46340;
            int mid = 0;
            int temp = 0;
            
            while(left <= right)
            {
                mid = left + ((right - left) >> 1);
                temp = mid * mid;
                
                if (temp == num)
                    return true;
                else if (temp >num)
                    right = mid - 1;
                else 
                    left = mid + 1;
            }
            
            return false;
        }
    };

Log in to reply
 

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