Binary search C++ solution takes cares of overflow


  • 0
    A

    using division instead of multiplication

    class Solution {
    public:
        bool isPerfectSquare(int num) {
            int low = 1, high = num;
            while (low <= high) {
                int mid = (low + high) / 2;
                int q = num / mid, r = num % mid;
                if (q > mid)
                    low = mid + 1;
                else if (q < mid)
                    high = mid - 1;
                else if (r)
                    return false;
                else
                    return true;
            }
            return false;
        }
    };

Log in to reply
 

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