Suffix Expression Summary

Source: Internet
Author: User

introduction of suffix Expressions

Suffix expression is characterized by computer operation is very convenient, need to use the stack; the computer processing process only needs to read in order, if the number is encountered, put into the stack, if the operator, then two stacks of digital out of the operation;

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

And the stack can be the general infix expression into a suffix expression, and the calculation of the suffix expression results, so this application in the calculator is very common;


Second, infix expression to convert to the suffix of expression

This method needs to follow several rules:

(1) If read into the operand, put directly into the output string;

(2) If you read a generic operator such as +-*/, put it on the stack, but you must check the top of the stack before you put it on the stack, and determine that the precedence of the stack operator is lower than the precedence of the operator being placed;

(3) If read in (, because the highest precedence of the left parenthesis, so put in the stack, but note that when the left parenthesis into the stack, then the lowest priority;

(4) If read in, then take the operator out of the stack into the output string until it is removed (note: () do not output to the output string;

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

third, the calculation of the suffix expression

The rules are as follows:

(1) If the operand, then put into the stack;

(2) If the operator, then take out the two operands in the stack, after the operation, the results into the stack;

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

Four, code

The following code is the helper code for the calculator, which can be computed quickly.

Input: Arithmetic (support bracket)

Output: Result string


Package org.xiazdong.Calculatorutils;



Import Java.util.Stack;  /** * Calculator Tool class * Complete integer, floating-point add, subtract, multiply, divide, bracket operation * * Taboo: If a. 5 indicates 0.5, the result is incorrect * @author Xiazdong */public class Calculatorutils {/** * converts infix expressions to suffix expression rules: 1. In the case of an operand, is added to the output stream 2. If it is (, add the stack; * 3. If it is), move the operator in the stack to the output stream until (until () not added to the output stream 4. If it is a generic operator (+-* */ , you need to check the precedence of the operator in the stack before adding the stack, and if the top priority of the stack is higher than the priority added, 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 output stream string StringBuilder builder = new StringBuilder ();
			3. Parse infix expression//3.1 If you are reading a number, read it until you read the operator 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 is over 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 + ""))); Or 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 + ""))); Or 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 ("there is a 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.