Created
February 26, 2015 03:28
-
-
Save dmnugent80/ddd30852ef2d41a1e35a to your computer and use it in GitHub Desktop.
Calculate Square Root
This file contains hidden or 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) { | |
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