LeetCode69 Sqrt(x)
2016-09-21 22:56
411 查看
题意:
Implement
Compute and return the square root of x.(Medium)
分析:
二分搜索套路题,不能开方开尽的时候,取结果整数位。
注意:判定条件中,用x / mid == mid而不是 mid * mid == x,否则可能出现int溢出。
代码:
Implement
int sqrt(int x).
Compute and return the square root of x.(Medium)
分析:
二分搜索套路题,不能开方开尽的时候,取结果整数位。
注意:判定条件中,用x / mid == mid而不是 mid * mid == x,否则可能出现int溢出。
代码:
class Solution { public: int mySqrt(int x) { if (x == 0) { return 0; } int start = 0, end = x; while (start + 1 < end) { int mid = start + (end - start) / 2; if (x / mid == mid) { return mid; } else if (x / mid > mid) { start = mid; } else { end = mid; } } if (x / end == end) { return end; } return start; } };
相关文章推荐
- [LeetCode-69] Sqrt(x)(求解平方根)
- [leetcode]69. Sqrt(x)
- [Java]Leetcode69 Sqrt(x)
- [leetcode] 69 Sqrt(x)
- LeetCode 69. Sqrt(x)
- [LeetCode] 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- Leetcode 69 Sqrt(x)
- 【LeetCode】69. Sqrt(x) 二分查找实现开平方函数
- leetcode 69 Sqrt(x)
- LeetCode 69. Sqrt(x)
- Leetcode 69. Sqrt(x) 解题报告【C库函数sqrt(x)模拟-求平方根】
- LeetCode 69. Sqrt(x) 解题报告
- leetcode oj java 69. Sqrt(x)
- 【LeetCode】69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- Leetcode 69. Sqrt(x)
- [leetcode] 【分治法】 69. Sqrt(x)
- Leetcode 69. Sqrt(x)
- leetcode69: Sqrt(x)