您的位置:首页 > 其它

[Leetcode 85] 69 Sqrt(x)

2013-07-25 05:43 661 查看
Problem:

Implement
int sqrt(int x)
.

Compute and return the square root of x.

Analysis:

If we simply use the naive algorithm to go through all the numbers from 0 until the square root, it will exceed the time limit. The hero is binary search.

We want such a number between 0 and n inclusively that x*x <= n and (x+1)*(x+1) > n. Not exactly x*x = n because its the integer square root. With this exit condition, we can easily use binary search to get the final result.

Code:

class Solution {
public:
int sqrt(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int s = 0, e = x;

while (s <= e) {
long long mid = (s + e) / 2, sq = mid * mid;

if (sq <= x && (mid+1) * (mid+1) > x)
return (int) mid;
else if (sq > x)
e = mid - 1;
else
s = mid + 1;
}

return -1;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: