Skip to content

Commit 6ebfbe1

Browse files
committed
adding algo
1 parent 7c90e0c commit 6ebfbe1

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def mySqrt(self, x: int) -> int:
6+
7+
left, right = 0, x
8+
9+
while left <= right:
10+
11+
mid = (left + right)//2
12+
13+
if mid ** 2 < x:
14+
left = mid + 1
15+
elif mid ** 2 > x:
16+
right = mid - 1
17+
else:
18+
return mid
19+
20+
return min(left, right)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_19\
3+
.sqrtx import Solution
4+
5+
class SqrtxTestCase(unittest.TestCase):
6+
7+
def test_even_sqrtx(self):
8+
solution = Solution()
9+
output = solution.mySqrt(x=4)
10+
target = 2
11+
self.assertEqual(output, target)
12+
13+
def test_odd_sqrtx(self):
14+
solution = Solution()
15+
output = solution.mySqrt(x=8)
16+
target = 2
17+
self.assertEqual(output, target)

0 commit comments

Comments
 (0)