Created
December 21, 2012 16:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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