Sqrt

Implement int sqrt(int x).

Compute and return the square root of x.

Solution:

  1. public class Solution {
  2. public int mySqrt(int x) {
  3. int lo = 1, hi = x;
  4. while (lo < hi) {
  5. int mid = lo + (hi - lo) / 2;
  6. if (mid < x / mid) {
  7. lo = mid + 1;
  8. } else {
  9. hi = mid;
  10. }
  11. }
  12. return (lo == x / lo) ? lo : lo - 1;
  13. }
  14. }