Skip to content

Commit 1a17fc4

Browse files
committed
adding algo
1 parent a8d2dfe commit 1a17fc4

3 files changed

Lines changed: 49 additions & 14 deletions

File tree

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+
right = mid - 1
15+
elif mid ** 2 < x:
16+
left = mid + 1
17+
else:
18+
return mid
19+
20+
return min(left, right)

tests/test_150_questions_round_14/test_sqrtx_round_14.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,17 @@
22
from src.my_project.interviews.top_150_questions_round_14\
33
.sqrtx import Solution
44

5-
class Solution:
6-
def mySqrt(self, x: int) -> int:
75

8-
left, right = 0, x
6+
class SqrtxTestCase(unittest.TestCase):
97

10-
while left <= right:
8+
def test_even_sqrtx(self):
9+
solution = Solution()
10+
output = solution.mySqrt(x=4)
11+
target = 2
12+
self.assertEqual(output, target)
1113

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

0 commit comments

Comments
 (0)