Created
March 5, 2019 04:16
-
-
Save malikzh/2fa8741fb994123c13e2e94360c9b612 to your computer and use it in GitHub Desktop.
Обратная польская нотация
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Обратная польская нотация | |
| * | |
| * @author Malik Zharykov | |
| */ | |
| function toRpn(statement) { | |
| let result = ''; | |
| let stack = []; | |
| // operator: priority | |
| const operators = { | |
| '+': 0, | |
| '-': 0, | |
| '*': 1, | |
| '/': 1, | |
| '^': 2 | |
| }; | |
| for (let i=0; i<statement.length; ++i) { | |
| const c = statement.charAt(i); | |
| if ((['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']).indexOf(c) >= 0 ) { | |
| result += c; | |
| } else if (c === '(') { | |
| stack.push(c); | |
| } else if (c === ')') { | |
| let s = stack.pop(); | |
| while (s && s != '(') { | |
| result += s; | |
| s = stack.pop(); | |
| } | |
| } else if (Object.keys(operators).indexOf(c) >= 0) { | |
| while ( operators[stack.slice(-1)[0]] >= operators[c]) { | |
| result += stack.pop(); | |
| } | |
| stack.push(c); | |
| } | |
| } | |
| let sym = ''; | |
| while (sym = stack.pop()) { | |
| result += sym; | |
| } | |
| return result; | |
| } | |
| // test | |
| console.log(toRpn('1 + 2 * 3 / (4+5) * (6+7)')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment