문제
정수 num1, num2가 매개변수로 주어질 때, num1을 num2로 나눈 몫을 return 하도록 solution 함수를 완성해주세요.
해답
1. Math.floor()사용하기
function solution(num1, num2) {
const answer = Math.floor(num1/num2);
return answer;
}
2. Math.trunc() 사용하기
trunc usuallly means truncate - cut off the decimal part of a number
이 문제는 정수들의 나눈 몫을 구하는거라서 Math.floor이 충분하지만
음수도 신경써야하면 trunc를 쓰는 것이 맞다
(ex. -3.7 -> -4)
function solution(num1, num2) {
return Math.trunc(num1 / num2);
}

3. 틸트 연산자
one tilde(~): bitwise NOT
- ⭐Bitwise operators in JS automatically convert decimal value to 32-bitsignedinteger BEFORE operating
=> Decimal is already gone before the fipping happens
- flips all bits of a 32-bit integer
- becomes - (x + 1)
ex) ~5 = -6
ex) ~4.9 = -5

two tilde(~~): double bitwise NOT
- trick used to truncate decimals, basically the same as Math.trunc()
- cancels out the inversion but keeps the integer conversion
- converts string to number / removes decimal part / converts bool to number
⭐only works correctly within 32-bit signed interger range (-2,147,483,648 to 2,147,483,647)
- 가독성 떨어져서 Math.trunc이 더 깔끔하다
ex) ~~4.9 = ~(-5) = 4
ex) ~~(-4.9) = ~(3) = -4
ex) ~~"15.8" = 15
ex) ~~true = 1
ex) ~~false = 0
function solution(num1, num2) {
return ~~(num1/num2);
}
4. Left Shift
function solution(num1, num2) {
return (num1 / num2)<<0;
}

그래서 1칸만큼 left shift하는 것은 (<<1)
2로 곱해주는 것과 유사하다.
근데 이 해결책은 left shift를 하지 않는다 (<<0)
대체 무엇이 일어나는걸까
위에 말했듯, Any bitwise operator in jS forces the value through ToInt32 Conversion
딱히 비트 연산을 할거는 아니지만 (left shift 안할거임, 2배 필요없음)
비트 연산자는 기본적으로 소수점을 없애주니
그 점을 이용하는 트릭같은 것이다.
'JS로 코테 준비하기 > 코테연습' 카테고리의 다른 글
| [JS코테0] 숫자 비교하기 (0) | 2026.03.03 |
|---|---|
| [JS코테0] JS 입력 받는 방법 (0) | 2026.03.02 |