367. Valid Perfect Square

Problem:

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Output: true

Example 2:

Input: 14
Output: false
</div> </div>

Solutions:

class Solution {
public:
    bool isPerfectSquare(int num) {
        int left = 1; // left is 1!
        int right = INT_MAX;

        while (left < right) {
            int mid = left + (right - left) / 2;
            if (num / mid > mid) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }

        return num % left == 0 && num / left == left;
    }
};

results matching ""

    No results matching ""