[367. Valid perfect square]](https://leetcode.com/problems/valid-perfect-square/)

AC Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    bool isPerfectSquare(int num) {
        /*
        // straight forward implementation
        
        int tmp = int(sqrt(num));
        return tmp * tmp == num;
        */
        
        // binary search
        int l = 0, r = 46341; // [l, r)
        while(r - l > 1) {
            int mid = (l + r) / 2;
            if(mid * mid <= num) {
                l = mid;
            } else {
                r = mid;
            }
        }
        
        return l * l == num;
    }
};