[Leetcode 85] 69 Sqrt(x)
2013-07-25 05:43
661 查看
Problem:
Implement
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:
View Code
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
相关文章推荐
- 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 OJ> 69. Sqrt(x)
- LeetCode_69---Sqrt(x)
- LeetCode69 Sqrt(x)
- [leetcode] 69.Sqrt(x)
- leetCode 69.Sqrt(x) (平方根) 解题思路和方法
- Leetcode——69. Sqrt(x)
- [leetcode]69. Sqrt(x)
- 【小熊刷题】sqrt(x) <Leetcode 69 Java>
- 个人记录-LeetCode 69. Sqrt(x)
- LeetCode:69. Sqrt(x)
- LeetCode-69-Sqrt(x) Python要用math.sqrt()
- 69. Sqrt(x) leetcode
- leetcode69 Sqrt(x)
- Leetcode 69 Sqrt(x) 求x开根号的整数部分