Leetcode代码学习周记——Sqrt(x)
2017-12-11 20:35
369 查看
题目链接:
https://leetcode.com/problems/sqrtx/description/
题目描述:
Implement
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函数调用,很明显使用这个函数对这道题来说和作弊无疑。
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函数调用,很明显使用这个函数对这道题来说和作弊无疑。
相关文章推荐
- Leetcode代码学习周记——Merge Two Binary Trees
- Leetcode代码学习周记——Add Two Nmubers
- Leetcode代码学习周记——Number Complement
- Leetcode代码学习周记——Longest Palindromic Substring
- Leetcode代码学习周记——Longest Substring Without Repeating Characters
- Leetcode代码学习周记——Container With Most Water
- Leetcode代码学习周记——Longest Common Prefix
- Leetcode代码学习周记——Judge Route Circle
- Leetcode代码学习周记——Two Sum
- Leetcode代码学习周记——3Sum
- Leetcode代码学习周记——Find Anagram Mappings
- Leetcode代码学习周记——Self Dividing Numbers
- Leetcode代码学习周记——Palindrome Number
- Leetcode代码学习周记——Reverse Integer
- Leetcode代码学习周记——Hamming Distance
- leetcode学习其他人的代码
- LeetCode编程练习 - Sqrt(x)学习心得
- 【leetcode】第69题 Sqrt(x) 题目+解析+JAVA代码
- GeoServer学习手记(二):代码下载及在Eclipse中加载
- vc学习历程(5)--经典的时钟代码