/*
* @lc app=leetcode.cn id=69 lang=typescript
*
* [69] x 的平方根
*/
//二分查找法
// @lc code=start
function mySqrt(x: number): number {
if (x === 1 || x === 0) {
return x;
}
let left = 0,
right = x,
squareRoot = 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
//采用x/mid比较而非mid*mid从而避免大数溢出
//if(mid*mid > X)
if (mid > x / mid) {
right = mid - 1;
squareRoot = mid - 1;
} else {
left = mid + 1;
squareRoot = mid;
}
}
return squareRoot;
}
/*
* @lc app=leetcode.cn id=69 lang=typescript
*
* [69] x 的平方根
*/
//牛顿迭代法
// @lc code=start
function mySqrt(x: number): number {
if (x === 1 || x === 0) {
return x;
}
let squareRoot = x;
while (squareRoot > x / squareRoot) {
//先取值为x,然后迭代令值等于值和 整数/值的平均数。
squareRoot = Math.floor((squareRoot + x / squareRoot) / 2);
}
return squareRoot;
}
// @lc code=end