๋ฌธ์
https://www.acmicpc.net/problem/1541
๋ฌธ์ ํ์ด
์ฒซ๋ฒ์งธ for๋ฌธ์์ [ '+1' , '-2' , '-3' , '+2' , '+2' , '3' ] ์ ๊ฐ์ arr๋ฅผ ์์ฑํ๊ณ
๋๋ฒ์งธ for๋ฌธ์์ answer์ ๊ณ์ฐํ๋ค
ํต์ฌ์ ์์ ์ดํ์ ์ฐ์์ ์ผ๋ก ์์๊ฐ ๋์ฌ ๋ ํด๋น ์์๋ ๊ฒฐ๊ตญ ์์๋ก ๊ณ์ฐํด์ผ ์ต์๊ฐ์ ๊ตฌํ ์ ์๋ค๋ ์ ์ด๋ค.
์์) 1-2+3+3 => 1-(2+3+3)
์ด๋ฐ์์ผ๋ก ์์์ดํ๋ก ์ฐ์์ ์ผ๋ก ๋ํ๋๋ ์์๋ ๋ชจ๋ ์์์ฒ๋ฆฌ ํ ๋ชจ๋ ์๋ค์ ํฉํ๋ฉด ์ต์๊ฐ์ ๊ตฌํ ์ ์๋ค.
let fs = require("fs");
let input = fs.readFileSync("/dev/stdin").toString().trim();
let num = "";
let numArr = [];
for (let i = 0; i < input.length; ++i) {
if (i === 0) {
if (input[i] === "-") {
num += input[i];
} else {
num += `+${input[i]}`;
}
} else {
if (input[i] === "+" || input[i] === "-") {
numArr.push(num);
num = input[i];
} else {
num += input[i];
}
}
if (i === input.length - 1) {
numArr.push(num);
}
}
let answer = 0;
for (let i = 0; i < numArr.length; ) {
let n = numArr[i];
if (n[0] === "-") {
let temp = -1 * Number(n);
let idx = i + 1;
while (idx < numArr.length && numArr[idx].at(0) === "+") {
temp += Number(numArr[idx]);
idx = idx + 1;
}
answer -= temp;
i = idx;
} else {
answer += Number(n);
++i;
}
}
console.log(answer);
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค[node.js] > 30804๋ฒ ๊ณผ์ผ ํํ๋ฃจ (0) | 2024.12.14 |
---|---|
๋ฐฑ์ค[node.js] > 1463๋ฒ 1๋ก ๋ง๋ค๊ธฐ (0) | 2024.12.13 |
๋ฐฑ์ค[node.js] > 17129๋ฒ ๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ (0) | 2024.12.09 |
๋ฐฑ์ค[node.js] > 12865๋ฒ ํ๋ฒํ ๋ฐฐ๋ญ (0) | 2024.12.08 |
๋ฐฑ์ค[node.js] > 15654๋ฒ N๊ณผ M (5) (0) | 2024.12.07 |