본문 바로가기
Algorithm

[백준] 단계별로 풀어보기 4단계 | Node.js

by Vintz 2021. 7. 9.
반응형

백준 알고리즘 4단계 while문

https://www.acmicpc.net/step/2

 

while문 단계

입력이 끝날 때까지 A+B를 출력하는 문제. EOF에 대해 알아 보세요.

www.acmicpc.net

01. A + B - 5 | 10952번

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let answer = '';
let i = 0;
const arr = [];
rl.on('line', (num) => {
  const input = num.split(' ');
  arr.push(input);
  while (i < arr.length) {
    const a = Number(input[0]);
    const b = Number(input[1]);
    if (a + b === 0) break;
    answer += `${a + b}\n`;
    i++;
  }
}).on('close', () => {
  console.log(answer);
  process.exit();
});

02. A + B - 4 | 10951번

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let answer = '';
let i = 0;
const arr = [];
rl.on('line', (num) => {
  const input = num.split(' ');
  arr.push(input);
  while (i < arr.length) {
    const a = Number(input[0]);
    const b = Number(input[1]);
    answer += `${a + b}\n`;
    i++;
  }
}).on('close', () => {
  console.log(answer);
  process.exit();
});

03. 더하기 사이클 | 1110번

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let i = 0;
rl.on('line', (num) => {
  const firstNum = Number(num);

  while (true) {
    const oneDigit = num % 10;
    const tenDigits = Math.floor(num / 10);
    const convertTenDigits = (num % 10) * 10;

    i++;

    sum = tenDigits + oneDigit;
    num = convertTenDigits + (sum % 10);

    if (firstNum === num) break;
  }
}).on('close', () => {
  console.log(i);
  process.exit();
});

더하기 사이클의 경우 생각보다 시간이 좀 걸렸다. 단순히 순서대로 처리를 하다보니 코드도 길어지고 몇몇 케이스는 답이 다르기도 했다. 그러다 좋은 문제풀이를 발견해서 풀게되었고 문제 풀이는 다음과 같다.

  1. N을 입력해 N의 십의 자릿수와 일의 자릿수를 더한다.
  2. N의 일의 자릿수를 십의 자릿수로 바꾼다.
  3. 2번의 값과 1번 값의 일의 자릿수를 더해 새로운 수를 구한다.
  4. N이 새로운 수가 된다.
  5. 처음 입력한 수와 새로운 수가 같아질 때까지 과정을 반복한다.

26을 예로 들어보자.

  1. 2 + 6 = 8
  2. 6 -> 60
  3. 60 + 8 = 68
  4. N = 68

이렇게 처음 입력한 수와 새로운 수가 같아질 때까지 과정을 반복하게 되면

  1. 68
  2. 6 + 8 = 14 -> 84
  3. 8 + 4 = 12 -> 42
  4. 4 + 2 = 6 -> 26

26은 4번만에 원래의 수로 돌아올 수 있다. 따라서 26의 사이클의 길이는 4이다.


더하기 사이클이 while문을 사용하기에 가장 좋은 문제 예시가 아닐까 생각된다. 생각보다 while문을 잘 사용하지 않아서 아직은 익숙하지도 않고 머리에 잘 안들어왔는데 이제 조금은 친해진 것 같다. 그래도 왠지 모르게 다른 반복문에 비해 사용이 좀 어렵다고 해야하나..? 잘 모르겠다. 

반응형