JavaScript/BOJ

2741. N 찍기

Lami 2022. 1. 21. 00:21

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().split('\n');

function solution() {
  for (let i = 1; i <= Number(input[0]); i++) {
    console.log(i);
  }
}

solution();

다음과 같이 반복문을 돌리며 출력을 했는데  시간초과가 떴었다.

이유를 몰라 검색을 해보니

 

이렇다고 한다.

 

이것을 보고 코드를 수정해서 아래와 같이 풀었더니 이번에는 시간초과가 뜨지 않고 정답처리가 된 것을 볼 수 있었다.

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().split('\n');

function solution() {
  let answer = '';
  for (let i = 1; i <= Number(input[0]); i++) {
    answer += i + '\n';
  }
  console.log(answer);
}

solution();

 

 

알게 된 점 : 반복문을 돌리며 console.log()를 찍으면 시간 초과가 날 수 있으니 되도록 반복문 안에서 console.log 사용하는 것을 자제하자!

 

 

/* 다른 언어 빠른 입출력 방법: https://www.acmicpc.net/board/view/22716 */