Star

LeetCode 367. Valid Perfect Square

Question

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:

1
2
Input: 16
Returns: True

Example 2:

1
2
Input: 14
Returns: False

Explanation

本题是查找平方根。Corner Case排除负数。用二分法找到值,注意overflow的问题,不能用乘法,用除法。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public boolean isPerfectSquare(int num) {
if(num <= 0) return false;
if (num == 1) return true;
int start = 0;
int end = num;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (num / mid == mid) {
start = mid;
} else if (num / mid < mid) {
end = mid;
} else {
start = mid;
}
}
if ( num*1.0 / start == start) return true;
if ( num*1.0 / end == end) return true;
return false;
}
}