본문 바로가기

Algorithm/Leetcode

[Top Interview 150 - Math] 69. Sqrt(x)

[Q] [Easy]

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.

 

  • do not use x ** 0.5 못 보고 아래와 같이 풀었는데 정답처리 됐다.
  • 근데 안된다니까 일단 빼고
  • 다른 답들을 찾아보니 이진탐색도 있고, 아래 import math 한 것도 있는데 일단 import math 로 해서 제출했는데 import math도 쓰면 안되는거 아닌가
  • 어렵다 어려워
# Answer

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

        # root 계산
        x_root = x ** (1/2)

        # 소수점 위의 자리만
        #ans = "{:.0f}".format(x_root)
        return int(x_root)

 

# Answer

import math

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

        # root 계산
        x_root = math.sqrt(x)

        # 소수점 위의 자리만
        #ans = "{:.0f}".format(x_root)
        return int(x_root)