367. Valid Perfect Square

Question

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


Code

public class Solution {
    public boolean isPerfectSquare(int num) {
        if (num == 0 || num == 1) return true;
        if (num < 0) return false;

        long l = 0L, h = (long) num, temp = (long) num;

        while (l <= h) {
            if (l + 1 == h) {
                if (temp > l * l && temp < h * h) return false;
            }
            long mid = l + (h - l) / 2;
            if (temp == mid * mid) return true;
            if (temp < mid * mid) {
                h = mid - 1;
            } else {
                l = mid + 1;
            }
        }

        return false;
    }
}

Solution

使用二分查找法。注意使用long来代替int进行计算,否则会因为溢出而出错。

推荐阅读更多精彩内容