Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Last active October 3, 2018 07:59
Show Gist options
  • Select an option

  • Save hsaputra/9c25672afa6e1e1e735f72c72c9ec37b to your computer and use it in GitHub Desktop.

Select an option

Save hsaputra/9c25672afa6e1e1e735f72c72c9ec37b to your computer and use it in GitHub Desktop.
class Solution {
public int mySqrt(int x) {
if (x == 1 || x == 0) {
return x;
}
long low = 1;
long high = x;
// Need to use binary search to fix y such that y*y = x
while (low < high && (high - low > 1)) {
long mid = (long) ((high + low)/2);
//System.out.println ("Mid is " + mid);
if (mid == x/mid) {
return (int) mid;
} else if (mid > x/mid) {
high = mid;
//System.out.println ("High is " + high);
} else {
low = mid;
//System.out.println ("Low is " + low);
}
}
return (int) low;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment