package com.myproject.demo.算法;
/**
* 实现 int sqrt(int x) 函数。
* <p>
* 计算并返回 x 的平方根,其中 x 是非负整数。
* <p>
* 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
* <p>
* 示例 1:
* <p>
* 输入: 4
* 输出: 2
* <p>
* 示例 2:
* <p>
* 输入: 8
* 输出: 2
* 说明: 8 的平方根是 2.82842...,
* 由于返回类型是整数,小数部分将被舍去。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/sqrtx
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author yuJie
* @since 2020/5/9
*/
public class x的平方根 {
public static int mySqrt(int x) {
if (x < 1) {
return 0;
}
if (x <= 3) {
return 1;
}
return 二分2(x);
}
//递归的二分超时
public static int 二分1(int x, int y) {
if (y * y <= x && (y + 1) * (y + 1) >= x) {
return y;
}
if (y * y < x && (y + 1) * (y + 1) < x) {
return 二分1(x, (x + y) / 2);
}
return 二分1(x, y / 2);
}
public static int 二分2(int x) {
int min = 0;
int max = x;
int ans = 0;
while (min <= max) {
int mid = min + (max - min) / 2;
if (mid * mid <= x) {
min = mid + 1;
ans = mid;
} else {
max = mid - 1;
}
}
return ans;
}
public static int mySqrt2(int x) {
return (int) Math.floor(Math.sqrt(x));
}
public static void main(String[] args) {
System.out.println(mySqrt(6));
}
}