代码拉取完成,页面将自动刷新
package com.hit.basmath.learn.binary_search;
/**
* 69. Sqrt(x)
* <p>
* Implement int sqrt(int x).
* <p>
* Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
* <p>
* Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
* <p>
* Example 1:
* <p>
* Input: 4
* Output: 2
* Example 2:
* <p>
* Input: 8
* Output: 2
* <p>
* Explanation: The square root of 8 is 2.82842..., and since
* the decimal part is truncated, 2 is returned.
*/
public class _69 {
/**
* Binary Search Solution
*
* @param x
* @return
*/
public int mySqrt(int x) {
if (x == 0) return 0;
int left = 1, right = Integer.MAX_VALUE;
while (true) {
int mid = left + (right - left) / 2;
if (mid > x / mid) {
right = mid - 1;
} else {
if (mid + 1 > x / (mid + 1)) {
return mid;
} else {
left = mid + 1;
}
}
}
}
/**
* Newton Solution
*
* @param x
* @return
*/
public int mySqrt2(int x) {
if (x < 2) return x;
double x0 = x;
double x1 = (x0 + x / x0) / 2.0;
while (Math.abs(x0 - x1) >= 1) {
x0 = x1;
x1 = (x0 + x / x0) / 2.0;
}
return (int) x1;
}
/**
* Brute Force Solution
*
* @param x
* @return
*/
public int mySqrt3(int x) {
if (x == 0) {
return 0;
}
for (int i = 1; i <= x / i; i++) {
// Look for the critical point: i*i <= x && (i+1)(i+1) > x
if (i <= x / i && (i + 1) > x / (i + 1)) {
return i;
}
}
return -1;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。