String arithmetic operations

Source: Internet
Author: User

Four arithmetic operations, of course, the most commonly used method is the inverse Polish method. Now the expression is converted from an infix expression to a suffix expression, and then it can be computed using the stack. In these two steps, it is estimated that no 300 or 400 lines of code can be implemented.

Infix expression to prefix suffix expression

The idea of converting an infix expression into a suffix expression is as follows:
Add a suffix expression to a number;
OPERATOR:
A. If it is '(', inbound stack;
B. If it is ')', add the operators in the stack to the suffix expression in sequence until '(' appears, and delete '(' from the stack '(';
C. If it is an operator other than parentheses, it is directly written into the stack when its priority is higher than the stack top operator other. Otherwise, from the top of the stack, an operator with a higher priority and a higher priority than the operator currently processed will pop up until one operator with a lower priority or a left bracket is encountered.

High priority can reduce the priority!

Manual conversion

Here I will give an infix expression: A + B * C-(D + E)
Step 1: brackets all operation units based on the operator's priority: the formula is changed to (a + (B * C)-(D + E ))
Step 2: Convert prefix and suffix expressions
Prefix: Move the operator number to the front of the corresponding brackets and change it to-(+ (A * (BC) + (de). Remove the brackets: -+ A * BC + de prefix child appears.
Suffix: Move the operator number to the end of the corresponding brackets and change it to (A (BC) *) + (de) +)-. Remove the brackets: ABC * + De +-suffix expression.

For example: Computing (2 + 1) * (13 + 5)

After conversion: (2 + 1) * (13 + 5)-> (2 1) + (13 5) +) *-> 2 1 + 13 5 + *
Here, the suffix expression is stored in vector <string> to implement stack calculation, as follows:

Int CAL (INT num1, int num2, string tag) {If ("+" = tag) {return num1 + num2;} else if ("-" = tag) {return num1-num2;} else if ("*" = tag) {return num1 * num2;} else {return num1/num2 ;}} int evalrpn (vector <string> & tokens) {int result = 0; stack <int> Nums; For (INT I = 0; I <tokens. size (); I ++) {string tag = tokens [I]; If (tag! = "+" & Tag! = "-" & Tag! = "*" & Tag! = "/") {// This Is A number nums. push (atoi (tag. c_str ();} else {// not a number int num2 = nums. top (); nums. pop (); int num1 = nums. top (); nums. pop (); Result = CAL (num1, num2, tag); nums. push (result) ;}} return result = nums. top ();}

In practice, the pen exam is like this., There is a string to represent a four arithmetic expression, requires the calculation of the correct value of this expression, for example: 5 + 17*8-4/2.

There are no parentheses in the question and more than half a piece of paper is left blank. Here we only need to consider the order of the four arithmetic operations. This is a special case of the above problem. The program can implement the calculation rules.

Idea: 1 + 5*6 + 6/2-5...
To build 1 + 5*6 + .... when the second plus sign is calculated, three numbers must be retained: first item 1, second item 5, and current item 6. There are two symbols + *, then, the priority of the comparison symbol is merged to update the symbol. Finally, consider 1 + 5, 1, and no numbers.

/** Hou Kai, 2014-9-16 * function: Four Arithmetic Operations */# include <iostream> # include <string> using namespace STD; int CAL (INT nnum1, char op, int nnum2) {If ('+' = OP) {return nnum1 + nnum2;} If ('-' = OP) {return nnum1-nnum2 ;} if ('*' = OP) {return nnum1 * nnum2;} If ('/' = OP) {return nnum1/nnum2 ;}} int calculate (string Str) {char op; // record the previous symbol char P; int num = 0, factor1, factor2; int stage = 0; If (Str. empty () return 0; For (INT I = 0; I <Str. size (); I ++) {If (STR [I]> = '0' & STR [I] <= '9 ') {num = num * 10 + (STR [I]-'0');} else {If (stage = 0) {factor1 = num; OP = STR [I]; stage = 1;} else if (stage = 1) {factor2 = num; P = STR [I]; Stage = 2;} else if (stage = 2) {// every time you enter this page, the status of a (OP) B (p) is saved, for example, 1 + 5 *. What you need to do here is to update a, B, op, if (P = '/' | P = '*') & (OP = '+' | op = '-') {factor2 = CAL (factor2, P, num); P = STR [I];} else {factor1 = CAL (factor1, op, factor2); factor2 = num; OP = P; P = STR [I] ;}} num = 0 ;}} float result; if (stage = 0) {return num;} If (stage = 1) {result = CAL (factor1, op, num); return result ;} if (P = '/' | P = '*') & (OP = '+' | op = '-')) {factor2 = CAL (factor2, P, num); Result = CAL (factor1, op, factor2);} else {factor1 = CAL (factor1, op, factor2 ); result = CAL (factor1, P, num);} return result;} int main () {string STR = "1 + 16*7 + 5*2 + 3 "; // 126 int res = calculate (STR); cout <res <Endl; System ("pause ");}

In this way, the program has been simplified a lot, and hundreds of lines of code should be able to handle it. Although it is not realistic to install it on the volume surface

String arithmetic operations

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.