Leetcode problem: valid perfect square
My answer is:
public class Solution {
public boolean isPerfectSquare(int num) {
int l = 0;
int r = (num>>1)+1;
while(l<=r) {
int mid = (l+r)>>1;
long temp = mid*mid;// why long
if( temp == num) return true;
else if( temp< num) l = mid+1;
else r=mid-1;
}
return false;
}
}
This answer time limit exceeds (when input 2^31-1). but if I changed l,r,mid to long (not int), it works. Why? Thanks
Aucun commentaire:
Enregistrer un commentaire