# LeetCode-Alg-367-Valid-Perfect-Square

## LeetCode-Alg-367-Valid-Perfect-Square

Posted by Jae on February 15, 2019

### 1、题目

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 ### 2、思路


### 3、实现

public boolean isPerfectSquare(int num) {
if (num < 0)
{
return false;
}
if (num == 1)
{
return true;
}
int low = 1;
int high = num;

while (low <= high)
{
int mid = low + (high - low) / 2;
int product = (int) Math.pow(mid, 2);
if (product == mid)
{
return true;
}else if(product > mid)
{
high = mid - 1;
}else if(product < mid)
{
low = mid + 1;
}
}

return false;
}


### 4、修改

public boolean isPerfectSquare(int num) {
if (num < 0)
{
return false;
}
if (num == 1)
{
return true;
}
int low = 1;
int high = num;

while (low <= high)
{
int mid = low + (high - low) / 2;
int div = num / mid;
int remainder = num % mid;
if (div == mid && remainder == 0)
{
return true;
}else if(div > mid)
{
low = mid + 1;
}else if(div < mid)
{
high = mid - 1;
}else
{
return false;
}
}

return false;
}


< script src = " / js / bootstrap.min.js " >