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
나의 풀이
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
return Math.floor(Math.sqrt(x))
};
문제를 풀며 느낀 점
- 많은 시행착오를 겪었는데 Example예시를 보고 풀어봤습니다. Math.sqrt()함수는 루트를 씌워서 제곱근을 반환하는 함수인데 4를 넣었을 때는 2로 깔끔하게 떨어지는 반면에 8을 2.2342234 소숫점 값이 나와서 Math.floor()를 이용해서 소수점 내림을 통한 값을 return 해주었습니다.
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
[Leet Code - midium] 08. String to Integer (atoi) (0) | 2023.02.28 |
---|---|
[Leet Code - eazy] 70.String to Integer (atoi) (0) | 2023.02.28 |
[프로그래머스] 피보나치 수 (0) | 2023.02.22 |
[프로그래머스] 올바른 괄호 (0) | 2023.02.22 |
[프로그래머스] 로그인 성공? (0) | 2023.02.22 |