Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created December 21, 2012 16:21
Show Gist options
  • Save zac-xin/4353800 to your computer and use it in GitHub Desktop.
Save zac-xin/4353800 to your computer and use it in GitHub Desktop.
Implement int sqrt(int x). Compute and return the square root of x.
public class Solution {
public int sqrt(int x) {
// Start typing your Java solution below
// DO NOT write main() function
long low = 0;
long high = x;
while(low <= high){
long mid = low + (high - low) / 2;
long result = mid * mid;
if(result == x){
return (int)mid;
} else if(result > x){
high = mid - 1;
} else{
low = mid + 1;
}
}
return (int)high;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment