ํฐ์คํ ๋ฆฌ ๋ทฐ
๋ฌธ์
ํ์์ฐ์ฐ์์ด ์ฃผ์ด์ง๋ฉด ์ฐ์ฐํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์ธ์.
๋ง์ฝ 3*(5+2)-9 ์ ํ์์ฐ์ฐ์์ผ๋ก ํํํ๋ฉด 352+*9- ๋ก ํํ๋๋ฉฐ ๊ทธ ๊ฒฐ๊ณผ๋ 12์
๋๋ค.
๋ฌธ์ ํ์ด
- ์ฐ์ฐ์์์ ์ซ์๊ฐ ๋์จ๋ค๋ฉด ์คํ์ ๊ณ์ ์ ์ฅ
- ์ดํ ์ฐ์ฐ์๊ฐ ๋์จ๋ค๋ฉด ๊ฐ์ฅ ์ต๊ทผ์ ์ ์ฅํ ๊ฐ๊ณผ ๊ทธ ์ด์ ์ ์ ์ฅํ ๊ฐ์ ์ถ์ถ
- ์ถ์ถํ ๋ ์ซ์๋ฅผ ํด๋น ์ฐ์ฐ์๋ฅผ ํตํด ํ๋์ ๊ฒฐ๊ณผ๊ฐ์ผ๋ก ๋์ถ
- ๋์ถ๋ ๊ฒฐ๊ณผ๊ฐ์ ์คํ์ ์ ์ฅ_์ดํ ๋ฐ๋ณต
์ฝ๋
function solution(p) {
let answer = 0;
let stack = [];
let regExp = /^[0-9]+$/;
for (let x of p) {
if (!regExp.test(x)) {
let rt = stack.pop();
let lt = stack.pop();
switch (x) {
case "+":
stack.push(lt + rt);
break;
case "-":
stack.push(lt - rt);
break;
case "*":
stack.push(lt * rt);
break;
case "/":
stack.push(lt / rt);
break;
default:
break;
}
} else {
stack.push(Number(x));
}
}
answer = stack.join("");
return answer;
}
let postfix = "352+*9-";
console.log(solution(postfix));
function solution(s){
let answer;
let stack=[];
for(let x of s){
if(!isNaN(x)) stack.push(Number(x));
else{
let rt=stack.pop();
let lt=stack.pop();
if(x==='+') stack.push(lt+rt);
else if(x==='-') stack.push(lt-rt);
else if(x==='*') stack.push(lt*rt);
else if(x==='/') stack.push(lt/rt);
}
}
answer=stack[0];
return answer;
}
let str="352+*9-";
console.log(solution(str));
'์๊ณ ๋ฆฌ์ฆ > ํ๊ทธ ๋ณ ํ์ด' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ]๊ต์ก๊ณผ์ ์ค๊ณ (0) | 2021.07.16 |
---|---|
[ํ]๊ณต์ฃผ ๊ตฌํ๊ธฐ (0) | 2021.07.15 |
๊ดํธ๋ฌธ์์ ๊ฑฐ (0) | 2021.07.11 |
[์คํ]์ฌ๋ฐ๋ฅธ ๊ดํธ (0) | 2021.07.10 |
๋ชจ๋ ์๋๊ทธ๋จ ์ฐพ๊ธฐ (0) | 2021.07.09 |
๋๊ธ