Here is the question from my friend (ex-colleague):
“I have a mathematical expression say (45 %2B ((4 – 25) %2B 2)) as a string. How can you evaluate it to find the result using JAVA programming language?”
But java is static, strongly typed, not-that-flexible language.
So, this cannot be provided as a language feature which leads me to either search for some available libraries or, write my won little library.
If you are reading this post, you know by now what my decision was:) Come on, what’s fun in searching for someone’s work ;) (Well, not always)
So, here it is… This would have been much simpler with dynamic language like Groovy… But, the requirement clearly said JAVA
Logic is quite simple. The given input is an infix expression. Use stack and keep pushing all the elements (including braces) till you encounter a closed brace.
Now, popping from the stack till you encounter an open brace will get you an operator and 2 operands.
Evaluate it and push back the result to continue the same logic till the end of the input string.