LeetCode Sqrt(x) (JavaScript)

2025. 12. 8. 12:38·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/sqrtx/description/

문제 설명

더보기

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

문제 풀이

x의 제곱수를 찾기 위해 먼저 다음과 같은 규칙을 찾을 수 있다.

x = 4 -> 2 -> result : 2

x = 8 -> 2.82... -> result : 2

x = 9 -> 3 -> result : 3

...

x = 15 -> 3.... -> result : 3

x = 16 -> 4 -> result : 4

즉, 중간의 값들의 제곱은 x보다 작거나 같다는 것을 알 수 있다.

이제 x의 값을 1부터 ~ x보다 작거나 같을 경우 까지 계속 증가시키면 큰 수인 경우 x를 1씩 증가시켜 시간초과 오류가 발생할 수 있다.

따라서 효율적인 x를 찾아내기 위해 이분 탐색을 이용하여 x의 범위를 효율적으로 구해야 한다.


left = 1, right = Math.floor(x / 2)

left, right를 통해 mid를 구하고 mid의 제곱이 x와 같다면 mid값을 리턴

제곱 값이 x보다 작다면 left의 범위를 늘려 다시 검사 (left = mid + 1)

제곱 값이 x보다 크다면 right의 범위를 줄여 다시 검사 (right = mid - 1)

left <= right인 경우 계속 반복을 해주며 가장 큰 제곱 값을 찾을 수 있도록 하고, 최종적으로 right의 값을 리턴해주면 됨.

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    if (x < 2) {
        return x;
    }

    let [left, right] = [1, Math.floor(x / 2)];

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

        if (square === x) {
            return mid;
        } else if (square < x) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return right;
};

결론

기준 값의 제곱이 x보다 작아지는 경우의 로직 (위 풀이에서는 squre과 x의 비교)

기준 값을 어떤식으로 관리를 할 것이냐

위 두 가지의 조건을 잘 생각해내는게 중요한 문제인 것 같다.

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Remove Duplicates from Sorted List (JavaScript)  (0) 2025.12.09
LeetCode Climbing Stairs (JavaScript)  (0) 2025.12.08
LeetCode Add Binary (JavaScript)  (0) 2025.11.27
LeetCode Plus One (JavaScript)  (0) 2025.11.27
LeetCode Spiral Matrix (JavaScript)  (0) 2025.11.26
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Remove Duplicates from Sorted List (JavaScript)
  • LeetCode Climbing Stairs (JavaScript)
  • LeetCode Add Binary (JavaScript)
  • LeetCode Plus One (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (215) N
      • 프론트엔드 (65) N
        • JavaScript (52) N
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (128) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (39) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Sqrt(x) (JavaScript)
상단으로

티스토리툴바