-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathSqrtx.cs
More file actions
29 lines (27 loc) · 768 Bytes
/
Sqrtx.cs
File metadata and controls
29 lines (27 loc) · 768 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Math.Lib
{
public class SqrtSln
{
public int MySqrt(int x)
{
if(x==0 || x==1)return x;
int lo = 0, hi = x;
while (lo - hi < -1)
{
//get [lo,hi] middle point,then compare pow2 to x,
// lo or hi is setted by mid
//so accelarate the process
long mid = lo + (hi - lo) / 2; //prevent overflowing
long pow2 = mid * mid; //prevent overflowing
if (pow2 < x) lo = (int)mid;
else if (pow2 > x) hi = (int)mid;
else return (int)mid;
}
return lo;
}
}
}