Skip to content

Instantly share code, notes, and snippets.

@gokhangirgin
Created September 18, 2017 20:16
Show Gist options
  • Save gokhangirgin/76b51343b36cfefaf6c297d0de0a6471 to your computer and use it in GitHub Desktop.
Save gokhangirgin/76b51343b36cfefaf6c297d0de0a6471 to your computer and use it in GitHub Desktop.
import java.util.*;
public class Main {
private static Stack<Integer> StackMachine = new Stack<>();
private static HashSet<Character> Operators = new HashSet<>(Arrays.asList(new Character[] {'+', '-', '*', '/'}));
public static void main(String[] args) {
String input = "13+62*7+*";
/***
*
* character | comment | stack
* -----------------------------------------------
* | | [empty]
* '1' | push 1 onto the stack |
* | | 1
* '3' | push 3 onto the stack |
* | | 1, 3
* '+' | perform addition |
* | | 4
* '6' | push 6 onto the stack |
* | | 4, 6
* '2' | push 2 onto the stack |
* | | 4, 6, 2
* '*' | perform multiplication |
* | | 4, 12
* '7' | push 7 onto the stack |
* | | 4, 12, 7
* '+' | perform addition |
* | | 4, 19
* '*' | perform multiplication |
* | | 76
*
***/
for(int i = 0; i < input.length(); i++){
char character = input.charAt(i);
if(Character.isDigit(character)){
StackMachine.push(Character.getNumericValue(character));
}
else if(Operators.contains(character)){
if(StackMachine.size() < 2) {
continue;
}
int result = calculate(StackMachine.pop(), StackMachine.pop(), character);
StackMachine.push(result);
}
}
if(!StackMachine.empty()){
System.out.println(String.valueOf(StackMachine.pop()));
}
}
private static int calculate(int x, int y, char operation) {
switch (operation){
case '+' :
return x + y;
case '-' :
return x - y;
case '*' :
return x * y;
case '/':
return x / y;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment