题目描述:
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
中文理解:给出一个整数,判断该数平方根是不是整数。
解题思路:暴力法,遍历从1-num/2,若i*i==num,则返回true。
代码(java):
class Solution {
public boolean isPerfectSquare(int num) {
if(num<1)return false;
if(num==1)return true;
for(int i=0;i<=num/2;i++){
if(i*i==num)return true;
else if(i*i>num)break;
}
return false;
}
}