Wednesday, June 29, 2016

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
Note:Be careful about the overflow when multiple two integers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Solution {
    public boolean isPerfectSquare(int num) {
        int l=0,r=num/2+1;//for num=1, for num=4. it is a waste of calculation after the 4. 
//but as a general approach, this keeps code concise
 while(l<=r){
  int m = l+(r-l)/2;
  long ans = (long)m*(long)m;//overflow
  if(ans==num)return true;
  if(ans>num)r=m-1;
  if(ans<num)l=m+1;
 }
 return false;
    }
}

No comments: