๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐Ÿ–ฅ dev-ruby

[๋ฐฑ์ค€-1541] ์žƒ์–ด๋ฒ„๋ฆฐ ๊ด„ํ˜ธ | node.js | silver2 ๋ณธ๋ฌธ

๋ฐฑ์ค€

[๋ฐฑ์ค€-1541] ์žƒ์–ด๋ฒ„๋ฆฐ ๊ด„ํ˜ธ | node.js | silver2

ruby_s 2022. 5. 26. 09:19
728x90
๋ฐ˜์‘ํ˜•
SMALL

๋ฌธ์ œ

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

 

1541๋ฒˆ: ์žƒ์–ด๋ฒ„๋ฆฐ ๊ด„ํ˜ธ

์ฒซ์งธ ์ค„์— ์‹์ด ์ฃผ์–ด์ง„๋‹ค. ์‹์€ ‘0’~‘9’, ‘+’, ๊ทธ๋ฆฌ๊ณ  ‘-’๋งŒ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๊ณ , ๊ฐ€์žฅ ์ฒ˜์Œ๊ณผ ๋งˆ์ง€๋ง‰ ๋ฌธ์ž๋Š” ์ˆซ์ž์ด๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์—ฐ์†ํ•ด์„œ ๋‘ ๊ฐœ ์ด์ƒ์˜ ์—ฐ์‚ฐ์ž๊ฐ€ ๋‚˜ํƒ€๋‚˜์ง€ ์•Š๊ณ , 5์ž๋ฆฌ๋ณด๋‹ค

www.acmicpc.net

 

ํ’€์ด

function solve() {
  let arr = [];
  for (let splited of input.split("-")) {
    let cnt = 0;
    let s = splited.split("+");

    for (const op of s) {
      cnt += +op;
    }
    arr.push(cnt);
  }

  return arr[0] + arr.slice(1).reduce((acc, curr) => acc - curr, 0);
}

const filePath =
  process.platform === "linux" ? "/dev/stdin" : "๋ฐฑ์ค€/silver/1541/testcase.txt";
const input = require("fs")
  .readFileSync(filePath)
  .toString()
  .trim()
  .split("\n")[0];
console.log(solve());

 

55-50+40-30+90

๋กœ ์˜ˆ์‹œ๋ฅผ ๋“ค์–ด ์„ค๋ช…ํ•˜๊ฒ ๋‹ค.

arr์— ๋ชจ๋‘ ํ‘ธ์‹œํ•œ ํ›„ ๊ฐ’์„ ์‚ดํŽด๋ณด๋ฉด [55, 90, 120] ์ด ๋“ค์–ด์žˆ๋‹ค.
-(๋งˆ์ด๋„ˆ์Šค)๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‹ค์Œ - ๊ฐ€ ๋‚˜์˜ฌ๋•Œ๊นŒ์ง€ arr์— ๊ทธ ์‚ฌ์ด์˜ ๊ฐ’์„ ๋”ํ•ด์„œ ํ‘ธ์‹œํ•ด์ค€๋‹ค.

๊ฒฐ๊ตญ 55, 50+40, 30+90 ์ด๋ ‡๊ฒŒ 3๊ฐœ์˜ ์š”์†Œ๊ฐ€ ๋“ค์–ด๊ฐ€๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด๋‹ค. ๊ทธ๋Ÿฐ ํ›„ ๋งจ ์ฒ˜์Œ ๊ฐ’ 55 ์—์„œ ๋’ค์— ๊ฐ’๋“ค์„ ์ญ‰ ๋นผ์ฃผ๋ฉด -๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ด„ํ˜ธ๋ฅผ ์นœ ์…ˆ์ด ๋œ๋‹ค. ๊ทธ ๊ฐ’์ด ์ตœ์†Ÿ๊ฐ’์ด ๋  ๊ฒƒ์ด๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
LIST