2023-10-23 23:16:24 +02:00
|
|
|
import readline from "node:readline"
|
2021-06-09 20:31:45 +02:00
|
|
|
|
|
|
|
const input = []
|
|
|
|
const readlineInterface = readline.createInterface({
|
|
|
|
input: process.stdin,
|
2023-10-23 23:16:24 +02:00
|
|
|
output: process.stdout,
|
2021-06-09 20:31:45 +02:00
|
|
|
})
|
2023-10-23 23:16:24 +02:00
|
|
|
readlineInterface.on("line", (value) => {
|
2021-06-09 20:31:45 +02:00
|
|
|
input.push(value)
|
|
|
|
})
|
2023-10-23 23:16:24 +02:00
|
|
|
readlineInterface.on("close", solution)
|
2021-06-09 20:31:45 +02:00
|
|
|
|
|
|
|
const operations = {
|
2023-10-23 23:16:24 +02:00
|
|
|
"+": (number1, number2) => number1 + number2,
|
|
|
|
"-": (number1, number2) => number1 - number2,
|
|
|
|
"*": (number1, number2) => number1 * number2,
|
|
|
|
"/": (number1, number2) => number1 / number2,
|
2021-06-09 20:31:45 +02:00
|
|
|
}
|
|
|
|
|
2023-10-23 23:16:24 +02:00
|
|
|
function solution() {
|
2021-06-09 20:31:45 +02:00
|
|
|
console.log(reversePolishNotation(input[0]))
|
|
|
|
}
|
|
|
|
|
|
|
|
function reversePolishNotation(value) {
|
|
|
|
if (value.length === 0) {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
const stack = []
|
2023-10-23 23:16:24 +02:00
|
|
|
const values = value.split(" ")
|
2021-06-09 20:31:45 +02:00
|
|
|
values.forEach((value) => {
|
|
|
|
const number = Number(value)
|
|
|
|
if (!isNaN(number)) {
|
|
|
|
stack.push(number)
|
|
|
|
} else if (operations.hasOwnProperty(value)) {
|
|
|
|
const number1 = stack.pop()
|
|
|
|
const number2 = stack.pop()
|
|
|
|
const operation = operations[value]
|
|
|
|
const result = operation(number2, number1)
|
|
|
|
stack.push(result)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
return stack.pop()
|
|
|
|
}
|