연습장
09. 홀짝 구분하기 본문
Q . 자연수 n이 입력으로 주어졌을 때 만약 n이 짝수이면 "n is even"을, 홀수이면 "n is odd"를 출력하는 코드를 작성해 보세요.
입력
100
출력
100 is even
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input = [];
rl.on('line', function (line) {
input = line.split(' ');
}).on('close', function () {
n = Number(input[0]);
});
자연수 n 에 대하여 홀짝 비교
즉 조건에 따라 다른 결과
if 문을 써도 좋지만 삼항연산자를 이용해보도록 하자 .
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input = [];
rl.on('line', function (line) {
input = line.split(' ');
}).on('close', function () {
n = Number(input[0]);
n % 2 == 0 ? console.log(n, "is even") : console.log(n , "is odd")
});
조건 ? 참 : 거짓
n 을 2로 나눈 나머지가 0 인가
true 일경우 짝수로 is even 을 출력
false 일경우 홀수로 is odd 를 출력 하면 된다 .
'프로그래머스 > 0단계' 카테고리의 다른 글
11. 문자열 섞기 (0) | 2023.06.17 |
---|---|
10. 문자열 겹쳐쓰기 (0) | 2023.06.17 |
08. 문자열 돌리기 (2) | 2023.06.17 |
07. 문자열 붙여서 출력하기 (0) | 2023.06.17 |
06. 덧셈식 출력하기 (0) | 2023.06.17 |