Last active
October 3, 2018 07:59
-
-
Save hsaputra/9c25672afa6e1e1e735f72c72c9ec37b to your computer and use it in GitHub Desktop.
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
| class Solution { | |
| public int mySqrt(int x) { | |
| if (x == 1 || x == 0) { | |
| return x; | |
| } | |
| long low = 1; | |
| long high = x; | |
| // Need to use binary search to fix y such that y*y = x | |
| while (low < high && (high - low > 1)) { | |
| long mid = (long) ((high + low)/2); | |
| //System.out.println ("Mid is " + mid); | |
| if (mid == x/mid) { | |
| return (int) mid; | |
| } else if (mid > x/mid) { | |
| high = mid; | |
| //System.out.println ("High is " + high); | |
| } else { | |
| low = mid; | |
| //System.out.println ("Low is " + low); | |
| } | |
| } | |
| return (int) low; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment