Search for a command to run...
Initialization
Binary search over candidate answers rather than over an array: low = 1, high = 28.
Binary Search on the Answer
1function floorSqrt(n) {2 let low = 1, high = n;//n: 28low: 1high: 28ans: 03 4 // Binary search on the answer space5 while (low <= high) {6 const mid = low + Math.floor((high - low) / 2);7 const val = mid * mid;8 9 // mid is small enough — look for a bigger one10 if (val <= n) {11 low = mid + 1;12 }13 // mid overshoots — look smaller14 else {15 high = mid - 1;16 }17 }18 19 // high ends on the largest value whose square fits20 return high;21}