您的位置:首页 > 其它

Leetcode 69. Sqrt(x)

2018-02-04 06:44 357 查看
原题:

Implement
int sqrt(int x)
.

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.


解决方法:

从该数本身开始,找到第一个平方不小于目标的数即是所求解。

代码:
int mySqrt(int x) {
if(x < 0)
return -1;
if (x <=1)
return x;
long i = x;
while(i*i > x){
i = ((i + x/i) >> 1);
}
return i;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C Leetcode