跳转至

367. Valid Perfect Square

Leetcode Math Binary Search

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

分析

这道题目与69. Sqrt(x)非常相像,只不过,Q69返回的是平方根值,这里返回的是是否是完全平方数。

public boolean isPerfectSquare(int num) {
    int lo = 0, hi = num;
    while (lo <= hi) {
        int mid = (lo + hi) >>> 1;
        double cmp = ((double) mid)*mid - num;
        if (cmp > 0) hi = mid - 1;
        else if (cmp < 0)  lo = mid + 1;
        else return true;
    }
    return false;
}