hahn

[LeetCode - C] 69. Sqrt(x) 본문

코딩테스트 연습/LeetCode(C - Easy)

[LeetCode - C] 69. Sqrt(x)

hahn 2022. 4. 18. 04:38
728x90
반응형
 

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

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

Solution 1

 

x의 제곱근을 소수점을 버린 뒤 리턴하는 문제

 

int의 최댓값의 제곱근은 46,340.95000105199.. 이므로

 

num * num에서 46340을 넘어가면

 

오버플로가 일어나기 때문에 46341이 되면 46340을 리턴

int mySqrt(int x)
{
    int num;
    
    num = 0;
    while (num * num <= x)
    {
        num++;
        if (num > 46340)
            return (46340);
    }
    return (num - 1);
}
728x90
반응형