Skip to content

Commit 92d4a35

Browse files
committed
sqrtx
1 parent 37ac11c commit 92d4a35

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Math/Math.Lib/Sqrtx.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
6+
namespace Math.Lib
7+
{
8+
public class SqrtSln
9+
{
10+
public int MySqrt(int x)
11+
{
12+
int lo = 0, hi = x;
13+
while (lo - hi < -1)
14+
{
15+
//get [lo,hi] middle point,then compare pow2 to x,
16+
// lo or hi is setted by mid
17+
//so accelarate the process
18+
long mid = lo + (hi - lo) / 2; //prevent overflowing
19+
long pow2 = mid * mid; //prevent overflowing
20+
if (pow2 < x) lo = (int)mid;
21+
else if (pow2 > x) hi = (int)mid;
22+
else return (int)mid;
23+
}
24+
return lo;
25+
}
26+
}
27+
28+
}

0 commit comments

Comments
 (0)