Created
October 14, 2012 02:10
-
-
Save chris-ramon/3887016 to your computer and use it in GitHub Desktop.
solves postfix expression
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace hadigari | |
{ | |
class Calculator | |
{ | |
double last_element; | |
double second_last_element; | |
double result; | |
public double postfixCalculator(string postfix) | |
{ | |
// Double data type would be useful for solve divisions like 2 / 3 | |
Stack<double> stk = new Stack<double>(postfix.Length); | |
for (int i = 0; i < postfix.Length; i++) | |
{ | |
// If postfix[i] is number we add it to the stack. | |
if (postfix[i] != '+' && postfix[i] != '-' && postfix[i] != '*' && postfix[i] != '/') | |
{ | |
// We push the number to the stack as double type, so we can solve | |
// expressions like 2 * 9 | |
// this cast the string to double data type, actually is not a string is a char | |
// because is just one element, like "1" so it is a char. | |
double number = Convert.ToDouble(postfix[i].ToString()); | |
stk.Push(number); | |
} | |
// If postfix[i] is operator like ( + , - , * , / ) we take the last two | |
// elements of the stack and calculate the result like 2 + 2. | |
else | |
{ | |
// We take and delete last element of the stack | |
last_element = stk.Pop(); | |
// We take and delete the second last element of the stack | |
second_last_element = stk.Pop(); | |
// We cast the postfix[i] to char, postfix[i] is a String, so we need a char | |
// like '+' | |
char _operator = Convert.ToChar(postfix[i]); | |
// Then we do a switch to perform the correct expression based on the operator | |
switch (_operator) | |
{ | |
case '+': | |
result = second_last_element + last_element; | |
break; | |
case '-': | |
result = second_last_element - last_element; | |
break; | |
case '*': | |
result = second_last_element * last_element; | |
break; | |
case '/': | |
result = second_last_element / last_element; | |
break; | |
} | |
// Finally we push the result of the expression to the stack. | |
stk.Push(result); | |
} | |
} | |
return stk.Pop(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment