[JS] 백준 10952. A+B -5

n-u·2022년 6월 23일
0

Algorithm

목록 보기
17/33
post-thumbnail

백준 10952. A+B -5

https://www.acmicpc.net/problem/10952

❌ 제출한 코드(틀렸다고함)

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

for (let i = 0; i < input.length - 1; i++) {
    let arrNum = input[i].split(' ').map((i) => +i);
    console.log(arrNum[0] + arrNum[1]);
}

어디서 어떤 점이 틀렸는지 아직도 모르겠음...

⭕ 제출한 코드(맞음)

https://gurtn.tistory.com/28

while (input[0][0] != 0) {
    const num = input.shift().split(' ');
    console.log(+num[0] + +num[1]);
}

결국에 해결할 수 없어서 참고하여 문제를 해결함

const num = input.shift().split(' ');

  • shift()메서드를 사용한 배열을 상수에 담으면 상수에는 shift()메서드에 의해 제거된 배열의 요소가 담긴다. 이 담긴 요소를 split(' ')를 이용해 각 요소를 나눠준다.
  • shift()메서드가 적용된 배열은 원 배열의 값이 변화된다.

    input = [ a, b, c];
    const num = input.shift();

    결과값

    console.log(num); -> a
    console.log(input) -> [ b, c]

  • 따라서 while문을 돌때마다 input 배열 안에 있는 요소들이 하나씩 제거되어 input[0]의 값이 변화된다.
  • num 상수에 담긴 배열의 인덱스 번호를 이용해 각 값들을 더한 값을 출력한다.
  • 마지막 입력값인 0, 0일때는 while문의 조건이 false이므로 while문이 종료 된다

풀면서 알게 된 것

  • while문에 대해서
  • 어떤 점에서 처음 제출한 코드가 틀렸는지 해결하지 못해 찜찜하다.
  • shift()메서드에 대해서
profile
기록하며 발전하는 삶

0개의 댓글