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
题意: 给出一个正整数,写一个方法来判断这个数字是否恰好是否个数字的平方值,
如果是,返回true,如果不是,返回false。
方法一:
依次求出每个数字的平方,判断是否等于num。
public class Solution { public boolean isPerfectSquare(int num) { for(int i=1; i<= num/i;i++){ if(i*i == num){ return true; } } return false; } }
方法二:
二分查找法,
public class Solution { public boolean isPerfectSquare(int num) { if(num < 1) return false; if(num == 1) return true; Long begin = (long)0; Long end = (long)num/2; while(begin <= end){ Long p = (begin + end)/2; if(p*p == num){ return true; }else if(p*p < num){ begin = p + 1; }else{ end = p - 1 ; } } return false; } }