topic:
Implement the int sqrt(int x) function.
Calculate and return the square root of x, where x is a non-negative integer.
Since the return type is an integer, only the integer part of the result is retained, and the decimal part will be discarded.
Example 1:
Input: 4
Output: 2
Example 2:Input: 8
Output: 2
Description: The square root of 8 is 2.82842...,
since the return type is an integer, the fractional part will be discarded.
Ideas:
Round down
- parseInt(Math.sqrt(x))
- (Math.sqrt(x)|0)
- (~~Math.sqrt(x))
Code:
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
while(x >= 0){
return parseInt(Math.sqrt(x));
}
};