Last active
August 29, 2015 14:04
-
-
Save pavelnganpi/2c4d952eccc3eb5b5b5b to your computer and use it in GitHub Desktop.
given a postfix mathematical expression, evaluate it
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
package test; | |
import java.util.Stack; | |
public class EvaluatePostfix { | |
public static int solution(String postfix){ | |
Stack<Integer> stack = new Stack<Integer>(); | |
int sum = 0; | |
int val1 = 0; | |
int val2 = 0; | |
for(int i =0; i<postfix.length(); i++){ | |
if(Character.isDigit(postfix.charAt(i))){ | |
stack.push(postfix.charAt(i) -'0'); | |
//System.out.println(stack.peek()); | |
} | |
else{ | |
//System.out.println(stack.peek()); | |
val1 = stack.pop(); | |
val2 = stack.pop(); | |
switch(postfix.charAt(i)){ | |
case '+': | |
stack.push(val1 + val2); | |
sum += val2; | |
break; | |
case '-': | |
stack.push(val1 - val2) ; | |
sum -= val2; | |
break; | |
case '/': | |
stack.push(val1 / val2) ; | |
sum /= val2; | |
break; | |
case '*': | |
stack.push(val1 * val2) ; | |
sum *= val2; | |
break; | |
} | |
//System.out.println(sum); | |
} | |
//System.out.println(stack.pop()); | |
} | |
return stack.pop(); | |
} | |
public static void main(String[]args){ | |
String test = "231*+9-"; | |
//solution(test); | |
System.out.println(solution(test)); | |
} | |
} | |
// below we are able to solve with more than 1 didigts, eg "10 20 30 * +" | |
package test; | |
import java.util.Stack; | |
public class EvaluatePostfix { | |
public static int solution(String postfix){ | |
Stack<Integer> stack = new Stack<Integer>(); | |
int sum = 0; | |
int val1 = 0; | |
int val2 = 0; | |
String[] str = postfix.split(" "); | |
for(int i =0; i<str.length; i++){ | |
if(Character.isDigit(str[i].charAt(0))){ | |
System.out.println(str[i]); | |
stack.push(Integer.parseInt(str[i])); | |
//System.out.println(stack.peek()); | |
} | |
else{ | |
//System.out.println(stack.peek()); | |
val1 = stack.pop(); | |
val2 = stack.pop(); | |
switch(str[i].charAt(0)){ | |
case '+': | |
stack.push(val1 + val2); | |
sum += val2; | |
break; | |
case '-': | |
stack.push(val1 - val2) ; | |
sum -= val2; | |
break; | |
case '/': | |
stack.push(val1 / val2) ; | |
sum /= val2; | |
break; | |
case '*': | |
stack.push(val1 * val2) ; | |
sum *= val2; | |
break; | |
} | |
//System.out.println(sum); | |
} | |
//System.out.println(stack.pop()); | |
} | |
return stack.pop(); | |
} | |
public static void main(String[]args){ | |
String test = "10 20 30 * +"; | |
//solution(test); | |
System.out.println(solution(test)); | |
// String man = "200"; | |
// int ch =Integer.parseInt(man); | |
//System.out.println(Char); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment