File tree Expand file tree Collapse file tree 1 file changed +19
-1
lines changed Expand file tree Collapse file tree 1 file changed +19
-1
lines changed Original file line number Diff line number Diff line change 48
48
* [ Github:#69 Sqrt(x)] ( /Math/Math.Lib/Sqrtx.cs )
49
49
* [ CSDN:#69 Sqrt(x)] ( http://blog.csdn.net/daigualu/article/details/72578272 )
50
50
* Tips:
51
- * careful to prevent overflowing for bas* digits, so declaring bas is long.
51
+ * careful to prevent overflowing for bas* digits.
52
+ ```C#
53
+ public int MySqrt(int x)
54
+ {
55
+ int lo = 0, hi = x ;
56
+ while (lo - hi < -1)
57
+ {
58
+ //get [lo,hi] middle point,then compare pow2 to x,
59
+ // lo or hi is setted by mid
60
+ //so accelarate the process
61
+ long mid = lo + (hi - lo) / 2; //prevent overflowing
62
+ long pow2 = mid * mid; //prevent overflowing
63
+ if (pow2 < x) lo = (int)mid;
64
+ else if (pow2 > x) hi = (int)mid;
65
+ else return (int)mid;
66
+ }
67
+ return lo;
68
+ }
69
+ ```
52
70
---
53
71
---
54
72
You can’t perform that action at this time.
0 commit comments