February 16, 2024

Viiisit [LeetCode] - 69. Sqrt(x)

#php#javascript#ruby

keep learning, keep coding!

Problem - Sqrt(x)

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

翻譯蒟蒻

給定一個正整數,找出不大於 x 的最大平方值所對應的整數。(不能用內建函數完成)



Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
let tmp = x;
while (tmp * tmp > x) {
tmp = Math.floor((tmp + x / tmp) / 2);
}
return tmp;
};

Solution - Ruby

1
2
3
4
5
6
7
def my_sqrt(x)
tmp = x
while tmp * tmp > x
tmp = (tmp + x / tmp) / 2
end
tmp
end

Solution - PHP

1
2
3
4
5
6
7
function mySqrt($x) {
$tmp = $x;
while ($tmp * $tmp > $x) {
$tmp = intval(($tmp + $x / $tmp) / 2);
}
return $tmp;
}

LeetCode 傳送門 - Sqrt(x)