Following code finds if a given number is a perfect square in O(lg N). How can I avoid hard-coding the corner case if (num === 1) { return true; }
given in the solution below? Any ideas?
var isPerfectSquare = function(num) {
let floor = 0, ceiling = num, mid;
// Corner case
if (num === 1) {
return true;
}
while (floor != ceiling) {
mid = floor + (ceiling - floor) / 2 | 0;
let mul = mid * mid;
if (mul === num) {
return true;
}
if (mul > num) {
ceiling = mid;
}
else if (mul < num) {
floor = mid+1;
}
}
return false;
};