Fork me on GitHub

[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

思路:

2分法。

不知道为什么int类型超时 但是long long就可以。。。

bool isPerfectSquare(int num)
{
    long long low = 1, high = num;    
    while (low <= high)
    {
        long long mid = low + (high - low) / 2;
        if (mid * mid == num)return true;
        else if (mid * mid < num)
        {
            low = mid + 1;
        }
        else high = mid - 1;
    }
    return false;
}

 

posted @ 2017-10-20 21:26  hellowOOOrld  阅读(195)  评论(0编辑  收藏  举报