Skip to content

Instantly share code, notes, and snippets.

@Chen-tao
Last active January 26, 2017 07:05
Show Gist options
  • Save Chen-tao/be81c50b4e80943b52e3e8f7957136db to your computer and use it in GitHub Desktop.
Save Chen-tao/be81c50b4e80943b52e3e8f7957136db to your computer and use it in GitHub Desktop.
//https://leetcode.com/problems/sqrtx/
public int mySqrt(int y) {
//return (int)Math.sqrt(x);
long L = 0, R = (long)y + 1;//[0,y)
long ans = 0;
while(L < R){
long mid = (L + R) / 2;// guess mid
if(guess(mid, y)){
ans = mid;
L = mid + 1;
} else {
R = mid;
}
}
return (int)ans;
}
public boolean guess(long x,long y){
return x * x <= y;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment