[LC] 367. Valid Perfect Square

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 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
Output: true

Example 2:

Input: 14
Output: false


class Solution {
    public boolean isPerfectSquare(int num) {
        if (num < 0) {
            return false;
        }
        int left = 0, right = num;
        while (left <= right) {
            long mid = left + (right - left) / 2;
            if (mid * mid == num) {
                return true;
            } else if (mid * mid < num) {
                left = (int)mid + 1;
            } else {
                right = (int)mid - 1;
            }
        }
        return false;
    }
}

 

以上是关于[LC] 367. Valid Perfect Square的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 367 Valid Perfect Square

367. Valid Perfect Square

367. Valid Perfect Square

367. Valid Perfect Square

leetcode 367. Valid Perfect Square

Leetcode 367. Valid Perfect Square