홀짝 구분하기

도비김·2024년 2월 22일
0
문제 설명

자연수 n이 입력으로 주어졌을 때 만약 n이 짝수이면 "n is even"을, 홀수이면 "n is odd"를 출력하는 코드를 작성해 보세요.


제한사항
  • 1 ≤ n ≤ 1,000

입출력 예

입력 #1

100

출력 #1

100 is even

입력 #2

1

출력 #2

1 is odd

※ 2023년 05월 15일 지문이 수정되었습니다.

solution

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]);
    if( n%2 == 1) console.log(`${n} is odd`)
    else console.log(`${n} is even`)
});

나머지는 %로 구한다.

다른풀이

const result = Number(line) % 2 ? 'odd' : 'even'
console.log(line, 'is', result)

console.log(n%2===0? `${n} is even`:`${n} is odd`)

let str = n;
str+= (n%2===0) ? " is even" : " is odd";
console.log(str);

삼항연산자가 더 편해보인다.

profile
To Infinity, and Beyond!

0개의 댓글