๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[์ธํ๋ฐ ์น์
6] ํ์์ ์ฐ์ฐ postfix (Javascript)
์ ๋ฃ ๊ฐ์์ธ ๊ด๊ณ๋ก ๋ฌธ์ ์ค๋ช
์ ์๋ตํฉ๋๋ค.
โ๏ธIdea Sketch
2021-06-27
1. str์ ์์๋ฅผ ๋ฐ๋ณต
for (let x of str) {
}
2. x๊ฐ ์ซ์๋ฉด stack.push();
3. x๊ฐ ์ฐ์ฐ๊ธฐํธ๋ฉด stack.pop(); ๋ก ์ซ์๋ฅผ ๊บผ๋ด์จ ํ stack[stack.length-1] ๊ณผ ์ฐ์ฐ
4. isNaN(s) ์ฌ์ฉ
- s์ด ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ true ๋ฆฌํด
if (isNaN(x)) {
let n = stack.pop();
if (x === '+') stack[stack.length-1] += n;
else if (x === '-') stack[stack.length-1] -= n;
else if (x === '*') stack[stack.length-1] *= n;
else if (x === '/') stack[stack.length-1] /= n;
}
else stack.push(x);
5. ๋ฌธ์์ด '5'๋ฅผ ์ซ์ 5๋ก ์ ํํด์ผํจ
- stack.push(); ํ ๋ ์ฒ๋ฆฌ
- ๋ฐฉ๋ฒ 1 : Number('5');
- ๋ฐฉ๋ฒ 2 : parseInt('5');
stack.push(paseInt(x));
โ๏ธ์์ค์ฝ๋
2021-06-27
function solution(str) {
let stack = [];
for (let x of str) {
if (isNaN(x)) {
let n = stack.pop();
if (x === '+') stack[stack.length - 1] += n;
else if (x === '-') stack[stack.length - 1] -= n;
else if (x === '*') stack[stack.length - 1] *= n;
else if (x === '/') stack[stack.length - 1] /= n;
}
else stack.push(parseInt(x));
}
return stack.pop();
}