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
分析:
二分。注意溢出!
1 public class Solution { 2 public boolean isPerfectSquare(int num) { 3 long begin = 1; 4 long end = num; 5 6 while (begin <= end) { 7 long mid = (end + begin) / 2; 8 if (mid * mid == num) { 9 return true; 10 } else if (mid * mid < num) { 11 begin = mid + 1; 12 } else { 13 end = mid - 1; 14 } 15 } 16 return false; 17 } 18 }