Postfix Operation

Problem

Write a program that outputs the result of the operation given a postfix expression.
If 3(5+2)-9 is expressed as a postfix expression, it is expressed as 352+9- and the result is 12.

input

  • Postfix expression is given in the first line. The length of the expression cannot exceed 50.
  • Expressions consist only of numbers 1 to 9 and +, -, *, and / operators.
352+*9-

output

  • Outputs the operation result.
12

Solution

O(n)

function solution(s) {
	let answer,
		tmp = '',
		result = 0;

	for (let i = 0; i < s.length; i++) {
		if (isNaN(parseInt(s[i]))) {
			let last1 = tmp[tmp.length - 2];
			let last2 = tmp[tmp.length - 1];
			let calc;

			result
				? (calc = eval(`${result} ${s[i]} ${last2}`))
				: (calc = eval(`${last1} ${s[i]} ${last2}`));

			result = calc;
			tmp = tmp.substring(0, tmp.length - 2);
		} else {
			tmp += s[i];
		}
	}

	answer = result;

	return answer;
}

use stack array

function solution(s) {
	let answer,
		stack = [];

	for (let x of s) {
		if (!isNaN(x)) stack.push(Number(x));
		else {
			let rt = stack.pop();
			let lt = stack.pop();
			stack.push(eval(`${lt} ${x} ${rt}`));
		}
	}

	answer = stack[0];
	return answer;
}