Inverse Polish algorithm to implement a arithmetic calculator

Source: Internet
Author: User
Tags arithmetic

The calculator is implemented in two steps:

1. The regular expression (infix expression) is processed into a suffix expression.

2. Computes a suffix expression.

The first step: infix such as: 1+ (2*3)-4/2, converted to suffix 123*+42/-.

Rule: From left to right traversal infix expression, if it is a number, directly out, if it is a symbol, then the priority, if the current symbol (including the right parenthesis) priority is not higher than the top of the stack, then out of the stack, until the priority is not satisfied (if the right parenthesis, Then until the left parenthesis is out of the stack, the suffix expression does not need the left and right brackets, and then the symbol is put into the stack. High-priority direct entry stack. So until it's done.

Step two: Calculate the suffix expression.

Rule: The suffix expression is traversed from left to right, if it is a number, directly into the stack, if it is a symbol, then pop up the top of the stack of two numbers, and this symbolic operation. The result of the operation is then stacked. Until the end of the calculation.

Inverse Polish algorithm to implement a arithmetic calculator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.