Created
January 28, 2013 13:53
-
-
Save pdu/4655641 to your computer and use it in GitHub Desktop.
Implement int sqrt(int x). Compute and return the square root of x. http://leetcode.com/onlinejudge#question_69
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 sqrt(int x) { | |
| if (x <= 0) | |
| return 0; | |
| int ret = 1; | |
| int left = 1, right = x; | |
| while (left <= right) { | |
| int mid = (left + right) >> 1; | |
| if (mid <= x / mid) { | |
| ret = max(ret, mid); | |
| left = mid + 1; | |
| } | |
| else | |
| right = mid - 1; | |
| } | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment