저장을 습관화

프로그래머스 LV.0 문자열 반복해서 출력하기 본문

코딩 테스트/프로그래머스 - 자바스크립트

프로그래머스 LV.0 문자열 반복해서 출력하기

ctrs 2023. 9. 7. 12:33

프로그래머스 LV.0 문자열 반복해서 출력하기

https://school.programmers.co.kr/learn/courses/30/lessons/181950

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1. 문제 명

프로그래머스 LV.0 문자열 반복해서 출력하기


2. 문제 설명

문자열 str과 정수 n이 주어집니다.

str이 n번 반복된 문자열을 만들어 출력하는 코드를 작성해 보세요.


3. 제한 사항

1 ≤ str의 길이 ≤ 10

1 ≤ n ≤ 5


4. 예시

입력 #1

string 5

 

출력 #1

stringstringstringstringstring

 


5. 기본 제공 코드

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 () {
    str = input[0];
    n = Number(input[1]);
});


6. 제출한 내 답

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 () {
  str = input[0];
  n = Number(input[1]);
  let a = "";
  for (i = 1; i <= n; i++) {
    a += str;
  }
  console.log(a);
});

 

6-2. VSC에 작성한 내용

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 () {
  str = input[0];
  n = Number(input[1]);
  let a = "";
  for (i = 1; i <= n; i++) {
    a += str;
  }
  console.log(a);
});


7. 특이사항

하긴 했는데 좀 더 깔끔한 방법이 있을것 같다...


8. 다른 사람이 작성한 답

8-1. .repeat() 메소드

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 () {
    str = input[0];
    n = Number(input[1]);
    console.log(str.repeat(n));
});

이런게 있지 않을까.. 생각은 했는데 역시나 있었다

.repeat() 기억해둬야지

https://redcow77.tistory.com/629

 

[Javascript] 문자열 일정하게 반복하기 - repeat() 함수

자바스크립트(Javascript)의 repeat() 함수 자바스크립트(Javascript)의 repeat() 함수는 주어진 문자열을 옵션의 count 만큼 반복하여 붙인 다음에 새로운 문자열로 반환하는 함수입니다. 문자열을 반복한

redcow77.tistory.com

 

8-2. 

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 () {
    str = '';
    n = Number(input[1]);
    for (let i = 0; i < n; i += 1) {
        str += input[0]
    }
    console.log(str)
});