백준 9498번 새싹 문제 node.js 풀이입니다.
[node.js] 백준 9498번 시험 성적
python에선 허용하는 문법인데 javascript에선 안된다...
1 < a < 2 비교식을 이용한 풀이
function solution() {
if (90 <= input <= 100) {
console.log("A");
} else if (80 <= input <= 89) {
console.log("B");
} else if (70 <= input <= 79) {
console.log("C");
} else if (60 <= input <= 69) {
console.log("D");
} else {
console.log("F");
}
}
python에선 허용했지만 안됨!
&&(and), ||(or) 연산자를 이용한 풀이
function solution() {
if (90 <= input && input <= 100) {
console.log("A");
} else if (80 <= input && input <= 89) {
console.log("B");
} else if (70 <= input && input <= 79) {
console.log("C");
} else if (60 <= input && input <= 69) {
console.log("D");
} else {
console.log("F");
}
}
가능
오답 이유
자바스크립트는 자유로운 언어라는 생각에 당연히 될 줄 알았던 비교 연산자 문법이 허용되지 않았다.
마무리
1 < a < 2
1 < a && a < 2
첫번째 비교식이 허용되더라도
&&(and), ||(or)
과 같은 비교 연산자를 사용하는 것이 속도적인 측면에서 더 효율적이다.
자바스크립트는 왼쪽부터 연산하는 언어인데
이때 만약 a = 0이게 되면
전체식에서 처음 마주하게 되는 1 < a 의 결과가 거짓이 되고
&& 비교 연산자 오른쪽 식은 판단하지 않고 넘어갈 수 있기 때문이다.
이를 쇼트 서킷(short circuit)이라 한다.
'IT > 알고리즘' 카테고리의 다른 글
[node.js] 백준 15552번 빠른 A+B (0) | 2022.08.08 |
---|---|
[node.js] 백준 14681번 사분면 고르기 (0) | 2022.07.27 |
[node.js] 백준 25083번 새싹 (0) | 2022.07.26 |