2 Star 10 Fork 2

国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_69.java 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
国斌 提交于 2020-03-05 20:48 . 优化题解
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;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助