본문 바로가기
IT/LeetCode

[LeetCode] 69. Sqrt(x)

by 강천구 2022. 8. 19.

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

 

Example 1:

Input: x = 4
Output: 2

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

 

Constraints:

  • 0 <= x <= 231 - 1
반응형

주어진 숫자의 루트 값보다 작은 정수 중 가장 큰 값을 출력하는 문제이다.

1. while문을 돌며 1부터 n까지 n*n이 주어진 값보다 클 때까지 1씩 늘려가며 정답을 구했다.

  문제 채점 기준 변경으로 Timeout이 발생하여 수정하였다.

2. 기존의 while문 안의 조건 찾는 부분 중 n^2이 주어진 x와 같은 불필요한 부분을 삭제하여 통과했다.

 

class Solution:
    def mySqrt(self, x: 'int') -> 'int':
        answer = 0
        while answer <=  x:
            if answer*answer > x:
                break
            else:
                answer += 1
        return answer-1

#1st - TimeOut
# class Solution:
#    def mySqrt(self, x: 'int') -> 'int':
#        answer = 0
#        while answer <=  x:
#            if answer*answer == x:
#                return answer
#            elif answer*answer > x:
#                break
#            else:
#                answer += 1
#        return answer-1

# Change scoring criteria

 

문제 출처 : https://leetcode.com/problems/sqrtx/

 

Sqrt(x) - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_69.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

'IT > LeetCode' 카테고리의 다른 글

[LeetCode] 83. Remove Duplicates from Sorted List  (0) 2022.10.27
[LeetCode] 70. Climbing Stairs  (0) 2022.08.19
[LeetCode] 67. Add Binary  (0) 2022.08.19
[LeetCode] 66. Plus One  (0) 2022.08.19
[LeetCode] 64. Minimum Path Sum  (0) 2022.08.17

댓글