其他分享
首页 > 其他分享> > 69. Sqrt(x)(js)

69. Sqrt(x)(js)

作者:互联网

69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.
题意:给给定数字开平方
代码如下:
/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
   if(x<4) return x==0 ? 0:1;
    
    var res=2*mySqrt(x/4)
    if((res+1)*(res+1)<=x && (res+1)*(res+1)>=0) return res+1;
    
    return res;
};

 

标签:square,return,truncated,int,Sqrt,js,integer,69,Input
来源: https://www.cnblogs.com/xingguozhiming/p/10512961.html