0

algorithm who have a string of math problem and print the answer

for example: "3+7+16" print 26 "8+7*4" print 36

30th Oct 2021, 7:04 AM
RLB
RLB - avatar
7 ответов
+ 2
RLB , can you please give an appropriate tag for the programming language? thanks!
30th Oct 2021, 11:16 AM
Lothar
Lothar - avatar
0
c#
30th Oct 2021, 11:18 AM
RLB
RLB - avatar
0
1. Convert the infix notation to postfix 2. Evaluate the postfix notation using a stack
31st Oct 2021, 1:12 PM
Alex
Alex - avatar
0
yeah... what the hell does it mean?
31st Oct 2021, 1:14 PM
RLB
RLB - avatar
0
"8+7*4" is called an infix expression. This means the operators (+, *) are in between the operands (8, 7, 4). Postfix means, that the operators are behind the values. "8+7*4" in postfix notation is "8 7 4 * +" Read this from left to right. If the token is a number, push it on the stack. If it's an operator, pop the last 2 values out of the stack, use the operator with these values and push the result on the stack. Push 8 (stack: [8]) Push 7 (stack: [8, 7]) Push 4 (stack: [8,7,4]) Hitting * => pop 2 values, multiply them, push the result. (stack: [8, 28]) Hitting + => pop 2 values, add them together. Push result. (stack: [36]) If you reach the end the result is the remaining value in the stack. The tricky part is to convert the infix notation to the postfix notation. But there are tons of resources explaining it. Try it yourself first and if you run into any problems ask again.
31st Oct 2021, 1:49 PM
Alex
Alex - avatar
0
ohh I got it bro but how to write it down?
31st Oct 2021, 1:56 PM
RLB
RLB - avatar
0
Read every char in the infix string, if it's a number, append it to the postfix string. If it is an operator put it on a stack. But if there are already operators on the stack you need to look at them first. While the rank of the current operator is less or equal the rank on top of the operator stack, pop the stack and append it to your postfix string. When reaching the end of the infix string pop every remaining operator to the postfix string. You'll need to insert some white spaces if your want to parse multi digit numbers. Try to solve your problem yourself first. If you can't solve it I'll help. Maybe ask Google for "infix to postfix algorithm" and "postfix evaluation using stack".
31st Oct 2021, 2:11 PM
Alex
Alex - avatar