您的位置:首页 > 编程语言

Leetcode代码学习周记——Sqrt(x)

2017-12-11 20:35 369 查看
题目链接:
https://leetcode.com/problems/sqrtx/description/
题目描述:

Implement 
int sqrt(int x)
.

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

实现函数 int sqrt(int x) 计算x的平方根(返回值为一个向下取整的整数)

三种题解(第二种超时):

一:直接调用cmath库的sqrt函数,返回值使用类型转换:

#include<cmath>
class Solution {
public:
int mySqrt(int x) {
double result = sqrt(x);
return (int)result;
}
};

二:从0开始向x/2 + 1遍历,直到找到平方根:
class Solution {
public:
int mySqrt(int x) {
for (int i = 0; i <= x / 2 + 1; i++) {
if (i * i > x) return i - 1;
if (i * i == x) return i;
}
return 0;
}
};

三:使用二分查找找到平方根:
class Solution {
public:
int mySqrt(int x) {
if (x != 0) {
int l = 1, r = 50000;
while (1) {
int mid = l + (r - l) / 2;
if (mid > x / mid) r = mid - 1;
else {
if ((mid + 1) > (x / (mid + 1))) return mid;
l = mid + 1;
}
}
}
return 0;
}
};

三种解法除了第二种会因为运行时检测不通过外均可以找到平方根,但个人认为这个题目出得不是很好,没有禁用cmath库的sqrt函数调用,很明显使用这个函数对这道题来说和作弊无疑。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: