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
本题开始做的时候并没有什么思路,后来看了tag的提示知道了可以用binary search来做,本题需要注意的是越界问题,代码如下:
1 public class Solution { 2 public boolean isPerfectSquare(int num) { 3 int left = 1; 4 int right = num; 5 while(left<=right){ 6 long mid = left+(right-left)/2; 7 if(mid*mid==num) return true; 8 else if(mid*mid<num) left = (int)mid+1; 9 else right = (int)mid-1; 10 } 11 return false; 12 } 13 }
有一个效率不高的做法,代码如下:
1 public boolean isPerfectSquare(int num) { 2 int i = 1; 3 while (num > 0) { 4 num -= i; 5 i += 2; 6 } 7 return num == 0; 8 }