题目原址
https://leetcode.com/problems/valid-perfect-square/description/
题目描述
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
Example2:
Input: 14
Returns: False
解题思路
该题是判断给定的数是否是一个能被开根号的数,判断的方法不能通过调用sqrt()
方法
这个如果用for(int i = 0; i< num ; i++)
循环的方式进行判断,是不能通过AC的,因为会有时间限制。那这里采用另外一种二插排序的方式来进行判断。先从中间开始判断,如果大于中间值,则将开始位置置于中间,否则将结束位置置于中间。
AC代码
class Solution {
public boolean isPerfectSquare(int num) {
boolean ret = false;
if(num == 0 || num == 1)
return true;
int start = 1, end = num;
while(start + 1 < end) {
int mid = start + (end - start) / 2; //中间值
int val = num / mid; //当前值
if(val == mid && num % val == 0){
ret = true;
break;
}else if(val > mid) {
start = mid;
}else {
end = mid;
}
}
return ret;
}
}