We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c1117f1 commit ca42283Copy full SHA for ca42283
top-interview-questions/69. Sqrt(x).cs
@@ -0,0 +1,31 @@
1
+// Binary search
2
+public class Solution {
3
+ public int MySqrt(int x) {
4
+ if (x == 0) return 0;
5
+ int left = 1, right = x;
6
+ while (left + 1 < right) {
7
+ int mid = left + (right - left) / 2;
8
+ if (mid == x / mid) {
9
+ return mid;
10
+ } else if (mid > x / mid) {
11
+ right = mid;
12
+ } else {
13
+ left = mid;
14
+ }
15
16
+ if (right <= x / right) return right;
17
+ return left;
18
19
+}
20
+
21
+// NewTon
22
23
24
25
+ long r = x;
26
+ while (r * r > x) {
27
+ r = (r + x / r) / 2;
28
29
+ return (int)r;
30
31
0 commit comments