# C#LeetCode刷题之#69-x 的平方根（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.

Input: 4

Output: 2

Input: 8

Output: 2

Explanation: The square root of 8 is 2.82842…, and since the decimal part is truncated, 2 is returned.

```public class Program {

public static void Main(string[] args) {
var n = 8;
var res = MySqrt(n);
Console.WriteLine(res);

n = 168;
res = MySqrt2(n);
Console.WriteLine(res);

n = 69;
res = MySqrt3(n);
Console.WriteLine(res);

}

private static int MySqrt(int x) {
//耍赖
return (int)(Math.Sqrt(x));
}

private static int MySqrt2(int x) {
//二分逼近，最后收敛于sqrt(x)
long res = x;
while(res * res > x) {
res = (res + x / res) / 2;
}
return (int)res;
}

private static int MySqrt3(int x) {
//魔数0x5f3759df，这个解法自行百度
//另外，这个解法LeetCode未AC，因为不支持unsafe
var i = 0L;
var num1 = 0F;
var num2 = 0F;
const float f = 1.5F;
num1 = x * 0.5F;
num2 = x;
unsafe {
i = *(long*)&num2;
i = 0x5f3759df - (i >> 1);
num2 = *(float*)&i;
}
num2 = num2 * (f - (num1 * num2 * num2));
num2 = num2 * (f - (num1 * num2 * num2));
return (int)(x * num2);
}
}```

```2
12
8```

MySqrt 的时间复杂度依赖于运行库的实现，MySqrt2 的时间复杂度为：  ，MySqrt3 的时间复杂度为：  。