You are given a string that represent an expression of digits and operands. E.g. 1+2*3, 1-2+4. You need to evaluate the string or the expression. NO BODMAS is followed. If the expression is of incorrect syntax return -1.
a) 1+2*3 will be evaluated to 9.
b) 4-2+6*3 will be evaluated to 24.
c) 1++2 will be evaluated to -1(INVALID).
Also, in the string spaces can occur. For that case we need to ignore the spaces. Like :- 1*2 -1 is equals to 1.
Source: Amazon Interview Question
It is strongly recommend to minimize the browser and try this yourself first.
The idea is simple start from the first character and traverse from left to right and check for errors like two consecutive operators and operands. We also keep track of result and update the result while traversing the expression.
Following is the program to evaluate the given expression.
Value of 1+2*5+3 is 18 Value of 1+2*3 is 9 Value of 4-2+6*3 is 24 1++2 is Invalid
The above code doesn’t handle spaces. We can handle spaces by first removing all spaces from the given string. A better solution is to handle spaces in single traversal. This is left as an exercise.
Time Complexity is O(n) where n is length of the given expression.
This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Program to evaluate the expression (√X+1)^6 + (√X-1)^6
- Queries to evaluate the given equation in a range [L, R]
- Program to find simple interest
- Program to find simple moving average
- Menu Driven C++ Program for a Simple Calculator
- Find the number of valid parentheses expressions of given length
- What is an Expression and What are the types of Expressions?
- Check if the given Binary Expressions are valid
- Simple Interest
- Number of Simple Graph with N Vertices and M Edges
- Times required by Simple interest for the Principal to become Y times itself
- Find if a degree sequence can form a simple graph | Havel-Hakimi Algorithm
- Write a program to reverse digits of a number
- Program to find parity
- Write an Efficient C Program to Reverse Bits of a Number
- Write a program to print all permutations of a given string
- Program to find amount of water in a given glass
- Program to convert a given number to words
- Efficient program to calculate e^x
- Efficient program to print all prime factors of a given number
Improved By : Mithun Kumar