Leetcode第69题
题目:
实现 int sqrt(int x) 函数。
- 计算并返回 x 的平方根,其中 x 是非负整数。
- 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
思路:
我们只需要找到 m 2 < x m^2<x m2<x的最大的m即可。可以采用二分法计算。
代码:
package leetcode.editor.cn;
//实现 int sqrt(int x) 函数。
//
// 计算并返回 x 的平方根,其中 x 是非负整数。
//
// 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
//
// 示例 1:
//
// 输入: 4
//输出: 2
//
//
// 示例 2:
//
// 输入: 8
//输出: 2
//说明: 8 的平方根是 2.82842...,
// 由于返回类型是整数,小数部分将被舍去。
//
// Related Topics 数学 二分查找
// 👍 748 👎 0
public class _69Sqrtx
{
public static void main(String[] args)
{
Solution solution = new _69Sqrtx().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution
{
public int mySqrt(int x)
{
int left = 0;
int right = x;
int mid;
int ans = -1;//需要单独定义一个变量,用来存放最后结果。因为mid要用来寻找有没有比ans更大的值
while (left <= right)
{
mid = (left + right) / 2;
if ((long)mid * mid <= x)//这里要进行强制转换,否则会溢出。
{
left = mid + 1;
ans = mid;
}
else
{
right = mid - 1;
}
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}