您的位置:首页 > Web前端

leetcode_Valid Perfect Square

2016-07-05 16:58 351 查看
[题目]

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<iostream>
#include<math.h>
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<<"("<<left<<","<<right<<")"<<endl;
//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<<isPerfectSquare(i)<<endl;
}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode