Created
May 17, 2015 18:40
-
-
Save shz117/14303a7db86f36c2553b to your computer and use it in GitHub Desktop.
sqrt(x)
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 int mySqrt(int x) { | |
if (x == 0) return 0; | |
double last = 0; | |
double cur = 1; | |
while (cur != last) { | |
last = cur; | |
cur = ( last + x / last ) / 2; | |
} | |
return (int) cur; | |
} | |
public int mySqrt(int x) { | |
if (x < 0) return -1; | |
if (x == 0 ) return 0; | |
int l = 1, r = x/2 + 1; | |
while (l < r) { | |
int m = (l+r) / 2; | |
if (m <= x / m && m + 1 > x / (m + 1)) { | |
return m; | |
} else if (m < x / m) { | |
l = m + 1; | |
} else { | |
r = m - 1; | |
} | |
} | |
return r; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment