[leetcode] problem 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

No.1

Input: 16

Output: true

No.2

Input: 14

Output: false

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public boolean (int num) {
int start = 1;
int end = num;

while (start <= end) {
int mid = start + (end - start) / 2;
float divide = num / (float) mid;

if (mid == divide)
return true;
else if (mid > divide)
end = mid - 1;
else
start = mid + 1;
}

return false;
}