Skip to content

Commit bd7ceae

Browse files
committed
feat: finish sqrt_x in python
1 parent 5815cfa commit bd7ceae

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

alternative/easy/sqrt_x.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def my_sqrt(x):
2+
left = 0
3+
right = x
4+
ans = -1
5+
6+
while left <= right:
7+
mid = left + (right - left) // 2
8+
9+
if mid > 0 and mid > x // mid:
10+
right = mid - 1
11+
else:
12+
ans = mid
13+
left = mid + 1
14+
15+
return ans
16+
17+
# Test cases
18+
assert my_sqrt(0) == 0
19+
assert my_sqrt(1) == 1
20+
assert my_sqrt(4) == 2
21+
assert my_sqrt(8) == 2
22+
assert my_sqrt(9) == 3
23+
assert my_sqrt(10) == 3
24+
assert my_sqrt(30) == 5
25+
assert my_sqrt(2147395599) == 46339

0 commit comments

Comments
 (0)