leetcode_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
【解法】
二分查找,从1 – num/2,因为除了1和4,一个数的开平方肯定小于这个数的一半,过程中注意溢出,因为两个比较大的int型相乘,可能溢出,因此程序中使用了long long类型。
【代码】

#include
#include
using namespace std;
bool isPerfectSquare(int num1)
{
    long long num = (long long) num1;
    if(num == 0 || num == 1 || num == 4)
    return true;
    int temp = num/2+1;
    int left = 1;
    int right = temp;
    while(left <= right)
    {
        //打印过程
        //cout<<"("<
        //long long防止溢出 
        long long mid = left + (right - left) / 2;
        if(mid * mid == num) return true;
        else if(mid * mid < num)
        left = mid + 1;
        else
        right = mid - 1;
    }
    return false;
}
int main(void)
{
    for(int i = 1;i <= 1024;i++)
    {
        if(isPerfectSquare(i))
        cout<"pause");
    return 0;
}

你可能感兴趣的:(LeetCode,算法,leetcode)