leetcode 367. Valid Perfect Square

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
Returns: True
Example 2:

Input: 14
Returns: False

不用sqrt,判断这个数是不是完全平方数。
用二分来实现sqrt进行判断。

class Solution {
public:
    bool isPerfectSquare(int num) {
        int l = 1;
        int r = num;
        if (num == 1) return true;
        int mid;
        while (l < r) {
            mid = l + (r - l + 1) / 2;
            if (mid > num / mid) {
                r = mid - 1;
            } else if (mid < num / mid){
                l = mid;
            } else {
                if (mid * mid == num) return true;
                else return false;
            }
            //cout << l << " " << r << endl;
        }
        //cout << mid << endl;
        return false;
    }
};
posted on 2018-02-28 18:23  Beserious  阅读(123)  评论(0编辑  收藏  举报