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;
    }
};

相关文章:

  • 2022-01-08
  • 2022-12-23
  • 2021-10-10
  • 2021-07-26
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
猜你喜欢
  • 2021-12-18
  • 2021-06-21
  • 2021-10-23
  • 2021-10-12
  • 2022-12-23
  • 2021-10-06
  • 2021-08-20
相关资源
相似解决方案