Summary of suffix expressions

Source: Internet
Author: User
Tags integer

First, the suffix expression introduction

The suffix expression is characterized by the computer operation is very convenient, need to use the stack, the computer processing process only need to read sequentially, if the number is encountered, then put in the stack, if the operator, then the two stack of numbers out of the operation;

For example, 1+2 suffix expression is 12+;

And the stack can turn the general infix expression into a suffix expression, and calculate the suffix expression to obtain the result, so this application is very common in the calculator;


Second, infix expression conversion to postfix expression

There are several rules to follow for this approach:

(1) If the read-in operand, then directly into the output string;

(2) If a general operator such as +-*/is read into the stack, it is necessary to check the top of the stack before putting it on the stack, and to make sure that the top operator has a lower precedence than the operator put in, and that the top operator needs to be placed in the output string if the precedence is lower;

(3) if read in (because the left parenthesis has the highest precedence, so put in the stack, but note that when the left parenthesis is placed in the stack, the priority is the lowest;

(4) if read in), the operator in the stack is taken out into the output string until it is removed (note: () does not output to the output string;

(5) Sequentially read the expression, if there are operators in the stack, then pop, and put the output string;

third, calculate the suffix expression

The rules are as follows:

(1) If it is an operand, it is put into the stack;

(2) If it is an operator, the two operands are taken out of the stack, and the result is put into the stack after the operation.

(3) until the last stack has only one element, this element is the result of the calculation;

Four, the code

The following code is the auxiliary code for the calculator, which allows for quick calculation.

Input: Arithmetic (support brackets)

Output: Result string


Package org.xiazdong.Calculatorutils;



Import Java.util.Stack;  /** * Calculator Tool class * Complete integer, floating point add, subtract, multiply, divide, parentheses operation * Taboo: if it appears. 5 means 0.5, the result is incorrect * @author xiazdong * */public class Calculatorutils {/** * converts infix expressions to suffix expression rules: 1. If it is an operand, it is added to the output stream 2. If yes (, add the stack; * 3. If it is), move the stack-in operator to the output stream until (() is not added to the output stream 4. If it is a general operator (+-* */ ), you need to check the precedence of the operators in the stack before joining the stack, and if the top priority of the stack is higher than the added precedence, move the top operator into the output stream, or add the operator directly; */public static string calculate (String str) {Retu
	RN Calculatereversepolish (Exchangetoreversepolish (str)); } private static string Exchangetoreversepolish (String str) {//1. Create Stack stack<string> s = new Stack<str
		Ing> ();
		2. Create the output stream string StringBuilder builder = new StringBuilder ();
			3. Parse infix expression//3.1 If the number is read, then read until the operator is read for (int i = 0, numlencount = 1; i < str.length (); i + = Numlencount) {
			char ch = str.charat (i);
			String operand = ch + "";
			Numlencount = 1;
				if ((ch + ""). Matches ("\\d{1}")) {numlencount = 1;
				char Nextchar = 0; if ((i + Numlencount) < sTr.length ()) {//The next character exceeds the boundary length Nextchar = Str.charat (i + numlencount);
						while ((Nextchar + "). Matches (" [. \\d{1}] ") {operand + = Nextchar;
							if ((i + Numlencount + 1) < Str.length ()) {Nextchar = Str.charat (i + numlencount + 1);
						numlencount++;
							} else {numlencount++;
						Break
				}}} operand + = "";

			Builder.append (operand);
				} else {if (ch = = ' (') {s.push (ch + ""); } else if (ch = = ' + ' | | ch = = '-') {while (s.size () > 0 && s.peek (). Matches ("[-+*/]")) {Builder.ap
					Pend (S.pop () + "");
				} s.push (ch + ""); } else if (ch = = ' * ' | | ch = = '/') {while (s.size () > 0 && s.peek (). Matches ("[*/]")) {Builder.appe
					nd (S.pop () + "");
				} s.push (ch + ""); } else if (ch = = ') ') {while (s.size () > 0 &&!s.peek (). Equals ("(")) {Builder.append (S.pop () + ""
					);
				} s.pop (); }}} while (S.size () > 0){Builder.append (S.pop () + "");
		} System.out.println (builder);

	return builder.tostring (); }/** * COMPUTE suffix expression * */private static String Calculatereversepolish (String str) {string[] splitstr = Str.split
		(" ");
		stack<string> s = new stack<string> ();
			for (int i = 0; i < splitstr.length; i++) {String ch = splitstr[i]; if (Ch.matches ("\\d+.\\d+") | |
			Ch.matches ("\\d+")) {s.push (CH);
					} else {if (S.size () >= 2) {String C1 = S.pop ();
					String C2 = S.pop (); if (ch.equals ("+")) {if (C1.contains (")") | | C2.contains ("."))
						{S.push (string.valueof (double.parsedouble (C2 + ") + Double. Parsedouble (c1 +")));
						} else{S.push (string.valueof (integer.parseint (C2 + ") + Integer. parseint (c1 +" "))); }} else if ("-". Equals (CH)) {if (C1.contains (".") | | C2.contains (".")) {S.push (string.valueof (double.parsedouble (C2 + ")-Double. Parsedouble (C1+ ""))));
						} else{S.push (string.valueof (integer.parseint (C2 + ")-Integer. parseint (c1 +" "))); }} else if ("*". Equals (CH)) {if (C1.contains (".") | | C2.contains ("."))
						{S.push (string.valueof (double.parsedouble (C2 + ") * Double. Parsedouble (c1 +" ")));
						} else{S.push (String.valueof ((integer.parseint (C2 + ") * Integer. parseint (c1 +" "))); }} else if ("/". Equals (CH)) {S.push (String.valueof ((double.parsedouble (C2 + ")/Double. parsedouble (C1 + ""))));}}
					else {System.out.println ("problem with the formula!");
				return null;
	}}} return S.pop ();
 }
}








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.