使用二分法:
public class Test69 {
@Test
public void test() {
System.out.println(mySqrt(0));
System.out.println(mySqrt(1));
System.out.println(mySqrt(4));
System.out.println(mySqrt(15));
System.out.println(mySqrt(16));
System.out.println(mySqrt(2147395599));
}
public int mySqrt(int x) {
int left = 0;
int right = x;
while (left <= right) {
int mid = left + (right - left) / 2;
if ((long) mid * mid > x) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
}
使用二分法:
public class Test367 {
@Test
public void test() {
System.out.println(isPerfectSquare(0));
System.out.println(isPerfectSquare(1));
System.out.println(isPerfectSquare(10));
System.out.println(isPerfectSquare(16));
}
public boolean isPerfectSquare(int num) {
if (num == 0) {
return false;
}
int left = 0;
int right = num;
while (left <= right) {
int mid = left + (right - left) / 2;
if ((long) mid * mid == num) {
return true;
}
if ((long) mid * mid < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
}