Algorithm training expression calculation time limit: 1.0s memory limit: 256.0MB Problem Description Enter a valid expression that contains only the plus and minus and parentheses, to find the value of the Expression. where except for the integer Division. Enter a line in the format that contains an Expression. The output format outputs the value of this Expression. Sample input 1-2+3* (4-5) sample output-4 data size and contract expression length not exceeding 100, expression operation is valid and the operation process is in int.
Topic Analysis:
operation priority: brackets → multiplication → add and subtract
For example 1-2+3* (4-5)
(1) calculation (4-5), The expression becomes 1-2+3*-1
(2) calculate 3*-1, The expression becomes 1-2+-3
(3) calculation 1-2, The expression becomes -1+-3
(4) calculate -1+-3, expression becomes-4
(5) results-4
based on this rule, we first put parentheses at both ends of the input expression to make the program repeat to calculate the subexpression in Parentheses. The calculation rule is like the previous Example. Example Code:
1 Importjava.io.BufferedReader;2 Importjava.io.IOException;3 Importjava.io.InputStreamReader;4 5 public classMain {6 public Static voidMain (string[] Args)throwsIOException {7BufferedReader br =NewBufferedReader (NewInputStreamReader (system.in));8StringBuilder expression =NewStringBuilder ("(" +br.readline () + ")");//expression, with parentheses on both sides of an input expression9StringBuilder temp =NewStringBuilder ();//holds a temporary expression, that is, each time a sub-expression in parentheses is storedTen while(true){ one intFrontbrackets = Expression.lastindexof ("(");//start the search from behind the expression and find the last "(" a intBackbrackets = Expression.indexof (")", frontbrackets);//search from the last "(" position to find the corresponding ")" - - if(frontbrackets = =-1) break;//If no expression needs to be computed, that is, expression has only one integer, the loop jumps out the -Temp.append (expression.substring (frontbrackets + 1, backbrackets));//the expression in this parenthesis is stored in temp -Expression.delete (frontbrackets, backbrackets + 1);//remove parentheses along with expressions in the original expression - + for(inti = 0; I < Temp.length (); I++) {//find the operator from the sub-expression, according to the operation principle, first multiplication and then minus - if(temp.charat (i) = = ' * ') {//If "*" is found, call calculation to perform the Operation +Calculation (temp, ' * '), i); ai = 0;//after the operation, I clear zero, convenient next time from the beginning to continue to look for the multiplication operator at } - - if(temp.charat (i) = = '/'){ -Calculation (temp, '/'), i); -i = 0; - } in } - to for(inti = 0; I < Temp.length (); I++) {//after the multiplication operator is found, the add and subtract cloud operators are started + if(temp.charat (i) = = ' + '){ -Calculation (temp, ' + '), i); thei = 0; * } $ Panax Notoginseng if(temp.charat (i) = = '-'){ -Calculation (temp, '-'), i); thei = 0; + } a } the +Expression.insert (frontbrackets, temp);//after the operation, the result is inserted in the position of the parentheses just removed, forming a new expression and continuing the loop calculation -Temp.delete (0, temp.length ());//empty temp To facilitate next expression calculation $ $ } - -System.out.println (expression);//Output Results the } - Wuyi /** the * Calculation Expressions - * @paramsrc-expression wu * @paramop operator - * @paramposition of the location operator in an expression about */ $ Private Static voidCalculation (StringBuilder src,CharOpintlocation ) { - intx = 0;//Number of Operations 1 - inty = 0;//Number of Operations 2 - intsum = 0;//sum = x (op) y a +String check = "0123456789+-";//detects whether the contents of an operator are either an array or a positive or negative number theStringBuilder temp =NewStringBuilder ();//store characters on both sides of the operator - $ if(location = = 0)return;//If you encounter a child indicating that only the decrement operator is in this case, and the first operator encountered is actually a sign that wants to represent a positive or negative number, the function returns and continues to look for the next operator the the intK = 0;//the number of the left and right sides of the search operator the for(k = location-1; k >= 0 && check.contains (src.charat (k) + ""); k--) {//search forward from one position to the left of the operator to find the first operand the Try{ - //If there are two operators in front of the number, the first is to connect to the number of the front, the second is to indicate the positive or negative of the number, then jump out of the loop, execute the following statement in //for example: 5+ (7+-5*+10), Search to 5 front, the first search to "-", found there is a "+", there is no operator in temp, then continue to execute, when the search to "+", found that there is no operator, jump out of the loop the if((src.charat (k) = = ' + ' | | Src.charat (k) = = '-') && (src.charat (k-1)! = ' + ' | | Src.charat (k-1)! = '-' )) the break; about if(temp.charat (0) = = ' + ' | | Temp.charat (0) = = '-') the break; the the}Catch(Exception E) { + //E.printstacktrace (); //no output exception to meet the problem output requirements - } the BayiTemp.insert (0, Src.charat (k));//insert content from the beginning of temp every time, ensuring that the contents of the reverse search are stored in the normal order of temp theSrc.deletecharat (k);//Delete the number in front of the operator, if there is a sign, also delete the } - -x = Integer.parseint (temp.tostring ());//the number of searches to be saved to x theTemp.delete (0, temp.length ());//Empty the Temp the the for(k = k + 2; K < src.length () && check.contains (src.charat (k) + "");) {//search backward from one position to the right of the operator, find the second operand, and add 2 because the top loop statement has since been reduced by one at the End. the - if((src.charat (k) = = ' + ' | | | Src.charat (k) = = '-') && (temp.length ()! = 0)) the break; the the temp.append (src.charat (k));94 Src.deletecharat (k); the } the they =integer.parseint (temp.tostring ());98Temp.delete (0, Temp.length ()); about - Switch(OP) {101 case+:102sum = x +y;103Src.deletecharat (k-1);//Delete operator104Src.insert (k-1, sum + "");//the result is stored in the operator position of SRC (the number of both sides of the operator has been removed from src, so inserting this position is equivalent to substituting the result for the sub-expression for the next Operation) the break;106 107 case‘-‘:108sum = x-y;109Src.deletecharat (k-1); theSrc.insert (k-1, sum + "");111 break; the 113 case‘*‘: thesum = x *y; theSrc.deletecharat (k-1); theSrc.insert (k-1, sum + "");117 break;118 119 case‘/‘: -sum = x/y;121Src.deletecharat (k-1);122Src.insert (k-1, sum + "");123 break;124 the default:126 break;127 } - }129}
Blue Bridge-cup Algorithm training ALGO-156 expression calculation