【LeetCode】 69. Sqrt(x) x 的平方根(Easy)(JAVA)
题目地址: https://leetcode.com/problems/sqrtx/
题目描述:
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
题目大意
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
解题方法
1、这种有上下限,还可以比较大小的一般都用二分法
2、二分查找,不断逼近找出 x 的平方根
class Solution {
public int mySqrt(int x) {
int start = 0;
int end = x;
while (start <= end) {
int mid = start + (end - start) / 2;
long sqrt = 1L * mid * mid;
if (sqrt == x) return mid;
if (sqrt > x) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return end;
}
}
执行用时 : 2 ms, 在所有 Java 提交中击败了 78.32% 的用户
内存消耗 : 37.1 MB, 在所有 Java 提交中击败了 5.05% 的用户