Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

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

left, right = 0, x

while left <= right:

mid = (left + right)//2

if mid ** 2 < x:
left = mid + 1
elif mid ** 2 > x:
right = mid - 1
else:
return mid

return min(left, right)
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def myPow(self, x, n):

if not n:
return 1
if n < 1:
return self.myPow(1/x, -n)
if n % 2:
return x*self.myPow(x,n-1)
else:
return self.myPow(x**2,n//2)
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
function mySqrt(x: number): number {
// Edge cases
if (x === 0 || x === 1) {
return x;
}

// Binary search for the square root
let left = 1;
let right = x;
let result = 0;

while (left <= right) {
const mid = Math.floor(left + (right - left) / 2);
const square = mid * mid;

if (square === x) {
return mid;
} else if (square < x) {
// Store the potential answer and search in the right half
result = mid;
left = mid + 1;
} else {
// square > x, search in the left half
right = mid - 1;
}
}

return result;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
function myPow(x: number, n: number): number {

if (!n){
return 1
}
if (n < 0){
return 1/myPow(x,-n)
}
if (n%2 !== 0){
return x * myPow(x,n-1)
}
return myPow(x*x,n/2)

};
17 changes: 17 additions & 0 deletions tests/test_150_questions_round_22/test_129_sqrtx_round_22.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import unittest
from src.my_project.interviews.top_150_questions_round_22\
.ex_129_sqrtx import Solution

class SqrtxTestCase(unittest.TestCase):

def test_even_sqrtx(self):
solution = Solution()
output = solution.mySqrt(x=4)
target = 2
self.assertEqual(output, target)

def test_odd_sqrtx(self):
solution = Solution()
output = solution.mySqrt(x=8)
target = 2
self.assertEqual(output, target)
Loading
Loading