367. Valid Perfect Square
Description
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
Solution
/**
* Solved with binary search algorithm
* @param {number} num
* @return {boolean}
*/
var isPerfectSquare = function(num) {
"use strict";
let min = 0, max = num;
while(min <= max) {
let mid = min + Math.ceil((max-min)/2);
let result = mid*mid;
if (result === num) {
return true;
} else if (result > num) {
max = mid-1;
} else {
min = mid+1;
}
}
return false;
};