[LeetCode] 69. Sqrt(x)

원숭2·2022년 1월 16일
0

LeetCode

목록 보기
5/51

문제

풀이

  1. 어떠한 내장함수나 오퍼레이터를 사용하지 못 하기 때문에 직접 찾아야 하므로 이진 탐색 사용
  2. 탐색에 성공 시 mid를 return하고, 못 하면 right를 return (while - else 구문)

코드

import math

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

0개의 댓글