Created
December 12, 2016 13:11
-
-
Save yamadayuki/b11732bea128659e4bb6701512818a87 to your computer and use it in GitHub Desktop.
Reverse Polish notation implementation using Stack.
This file contains 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
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_A | |
// Test Case | |
// Input | |
// 34 116 + 20 5 - 5 - 1 * + | |
// Output | |
// 160 | |
var input = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split(' ').map(function(value) { | |
if (!isNaN(parseInt(value))) { | |
return parseInt(value); | |
} else { | |
return value; | |
} | |
}); | |
function push(value, container) { | |
container.push(value); | |
return container; | |
} | |
function add(container) { | |
var b = container.pop(); | |
container.push(container.pop() + b); | |
return container; | |
} | |
function sub(container) { | |
var b = container.pop(); | |
container.push(container.pop() - b); | |
return container; | |
} | |
function mul(container) { | |
var b = container.pop(); | |
container.push(container.pop() * b); | |
return container; | |
} | |
function calc(operation, container) { | |
switch (operation) { | |
case '+': | |
container = add(container); | |
break; | |
case '-': | |
container = sub(container); | |
break; | |
case '*': | |
container = mul(container); | |
} | |
return container; | |
} | |
var container = []; | |
input.forEach(function (value) { | |
if (typeof value === 'number') { | |
push(value, container); | |
} else { | |
calc(value, container); | |
} | |
}); | |
console.log(container[0]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment