[leetcode]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 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False

题意:

验证完全平方数

思路:

二分查找,可回顾之前[leetcode]278. First Bad Version首个坏版本 笔记

需要注意的是类型声明为long

代码:

 class Solution {
public boolean isPerfectSquare(int num) {
long left = 0;
long right = num; while (left <= right) {
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;
}
}
上一篇:iOS代码技巧之判断设备及状态


下一篇:2017 Multi-University Training Contest - Team 9 1003&&HDU 6163 CSGO【计算几何】