Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 28, 2013 13:53
Show Gist options
  • Select an option

  • Save pdu/4655641 to your computer and use it in GitHub Desktop.

Select an option

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
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