[Leetcode] 69. Sqrt(x)

2024. 4. 4. 06:40Algorithm

Problem:

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.
 

Example 1:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.
Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
 

Constraints:

0 <= x <= 231 - 1

 

Solution1:

class Solution:
    def mySqrt(self, x: int) -> int:
        left,right = 0, x 
        mid = 0 
        while left <= right:
            mid = (left + right) // 2 
            if (mid*mid) == x:
                return mid 
            elif x < (mid*mid):
                right = mid - 1 
            else:
                left = mid + 1 
        return right

이 문제는 특정언어의 내장함수와 operator를 사용하면 안 된다는 조건이 있다. 나는 어떻게 제곱근을 표현할지 몰라 Solution을 참고했다. 이번 문제에서 Binary Search를 사용하게 될 줄 몰랐다. 이번 문제를 통해서 Binary Search는 내가 찾고자 하는 값이 있을 때 사용하자라는 뜻을 얻게 되었다.