Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 26, 2015 03:28
Show Gist options
  • Save dmnugent80/ddd30852ef2d41a1e35a to your computer and use it in GitHub Desktop.
Save dmnugent80/ddd30852ef2d41a1e35a to your computer and use it in GitHub Desktop.
Calculate Square Root
public class Solution {
public int sqrt(int x) {
long low = 1;
long high = x/2;
if (x == 0){
return 0;
}
if (x < 4){
return 1;
}
while (low <= high){
long mid = (low + high) /2;
if (mid == x/mid){
return (new Long(mid).intValue());
}
if (mid < x/mid){
low = mid+1;
}
else{
high = mid-1;
}
}
return (new Long(low-1).intValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment