Java go test solution 4

Source: Internet
Author: User

Use your own stack to evaluate an integer expression. The supported operators include () */+.

1. */higher than +-

2. operators with the same priority in the expression are calculated from left to right.

3. function input string "1 + (4-3) * 5/5", function returns 2


Use stack in api

Convert prefix to suffix



/**
* Infix expression to suffix expression
*/
Import java. util. ArrayList;
Import java. util. Iterator;
Import java. util. List;
Import java. util. Stack;


Public class ExpressConvert {

/**
* Priority comparison
* @ Param operator1 comparison value
* @ Param operator2 is compared
* @ Return: returns false if the return value is less than or equal to false. returns true if the return value is greater than false.
*/
Public boolean comparePrior (char operator1, char operator2 ){
If ('= operator2 ){
Return true;
}
If ('*' = operator1 | '/' = operator1 ){
If ('+' = operator2 | '-' = operator2 ){
Return true;
}
}
Return false;
}

/**
* Convert to a suffix expression:
* 1. If it is "(", it is directly pushed into the stack.
* 2. If it is ")", add the operator from the stack pop-up in sequence to the end of the array newExpressionStrs, knowing that "(";
* 3. If it is not a bracket, compare the scanned operators with the operators at the top of the stack. If the scanned operator has a higher priority than the stack top operator, the operator is pushed to the stack. Otherwise, the operators in the stack pop-up will be added to the end of the array newExpressionStrs until the operator or stack with a lower priority than the scan is empty, and the scanned operator is pushed into the stack. In this way, scan sequentially until the end of the scan. If the scan is complete and there are still elements in the stack, the suffix expression is displayed and added to the end of the array newExpressionStrs.
* @ Param expressionStrs
* @ Return
*/
Public List ToSuffixExpression (char [] expressionStrs ){
// A new expression
List NewExpressionStrs = new ArrayList ();
Stack Stack = new Stack ();
For (int I = 0; I <expressionStrs. length; I ++ ){
If ('= (expressionStrs [I]) {// if it is left parenthesis
Stack. push (expressionStrs [I]);
} Else if ('+' = expressionStrs [I] | '-' = expressionStrs [I] | '*' = expressionStrs [I] | '/' = expressionStrs [I]) {

If (! Stack. empty () {// retrieves the first-in-stack Operator
Character s = stack. pop ();
If (comparePrior (expressionStrs [I], s) {// if the stack value has a higher priority than the value to be imported into the stack, It is pushed into the stack.
Stack. push (s );
} Else {// otherwise retrieve the value
NewExpressionStrs. add (s );
}
}

Stack. push (expressionStrs [I]);
} Else if (')' = expressionStrs [I]) {// if it is ')', it goes out of the stack until it encounters '('
While (! Stack. empty ()){
Char s = stack. pop ();
If (! ('= S )){
NewExpressionStrs. add (s );
} Else {
Break;
}
}
} Else {
NewExpressionStrs. add (expressionStrs [I]);
}
}
While (! Stack. empty ()){
Char s = stack. pop ();
NewExpressionStrs. add (s );
}
Return newExpressionStrs;
}

Public static void main (String [] args ){

String expressionStr = "5 + (4-5 + 1)-4 + (6-5 + 3) + 2 ";
// Split it into an array of expressions
Char [] expressionChrs = expressionStr. toCharArray ();

List NewExpressionStrs = new ExpressConvert (). toSuffixExpression (expressionChrs );
Iterator Iter = newExpressionStrs. iterator ();
While (iter. hasNext ()){
System. out. print (iter. next ());
}
}
}


// Use the stack to calculate the suffix expression value

Principle: Put the suffix expression in the list or array only

Loop removal suffix expression if the retrieved number is pushed to the stack. If the operator is used, the value in the stack is pop, and the number (+-*/) After pop is used -*/) first pop the number, and then put the result back into the stack.

Until the last value pops out of the stack.

Import java. util. Iterator;
Import java. util. List;


Import calculator. ExpressConvert;
Import dataStructure. MyStack;


Public class Test4 {




Public static void main (String [] args ){
MyStack MS = new MyStack ();
String str = "1 + (4-3) * 5/5 ";
Char chr [] = str. toCharArray ();
ExpressConvert ec = new ExpressConvert ();
List List = ec. toSuffixExpression (chr );
Iterator Iter = list. iterator ();
While (iter. hasNext ()){
Character c = iter. next ();
Try {
If (c = '+' | c = '-' | c = '*' | c = '/'){

Int a = Integer. parseInt (ms. pop (). toString ());
Int B = Integer. parseInt (ms. pop (). toString ());


Int n = 0;
Switch (c ){

Case '+': n = B + a; break;
Case '-': n = B-a; break;
Case '*': n = B * a; break;
Case '/': n = B/a; break;
}

Ms. push (n );
} Else {
Ms. push (c );
}

} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
System. out. println (ms. getSize ());
Try {
System. out. println (ms. pop ());
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
} E. printStackTrace ();
}
}
}



// Customize the stack (simple ).

Import java. util. ArrayList;
Import java. util. List;
Import java. util. Stack;


/**
* Data Structure Stack
* Array Implementation
* @ Author Administrator
*
*/
Public class MyStack {


Private int top; // stack top
Private Object [] obj;
Private int max = 10;
Private int size; // stack size
Public MyStack (){
This. obj = new Object [max];
}
Public boolean empty (){
If (size = 0)
Return true;
Return false;
}
Public T pop () throws Exception {

If (size = 0) throw new Exception ("the following table is out of bounds ");
Object objct = obj [top];
Obj [top --] = null;

Size --;
Return (T) objct;
}
Public T push (Object o) throws Exception {
If (size = max) throw new Exception ("subscript out of bounds ");
Obj [++ top] = o;
Size ++;
Return (T) obj [top];
}
Public int getSize (){
Return size;
}
Public static void main (String [] args ){
MyStack MS = new MyStack ();
Try {
Ms. push ("aaa ");
Ms. push ("bbb ");
Ms. push ("ccc ");
System. out. println (ms. pop () + "" + ms. pop ());
System. out. println (ms. size );
System. out. println (1 + (4-3) * 5/5 );
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}


// Use a custom stack with a prefix converted to an infix

/**
* Infix expression to suffix expression
*/
Import java. util. ArrayList;
Import java. util. Iterator;
Import java. util. List;


Import dataStructure. MyStack;


Public class ExpressConvert {

/**
* Priority comparison
* @ Param operator1 comparison value
* @ Param operator2 is compared
* @ Return: returns false if the return value is less than or equal to false. returns true if the return value is greater than false.
*/
Public boolean comparePrior (char operator1, char operator2 ){
If ('= operator2 ){
Return true;
}
If ('*' = operator1 | '/' = operator1 ){
If ('+' = operator2 | '-' = operator2 ){
Return true;
}
}
Return false;
}

/**
* Convert to a suffix expression:
* 1. If it is "(", it is directly pushed into the stack.
* 2. If it is ")", add the operator from the stack pop-up in sequence to the end of the array newExpressionStrs, knowing that "(";
* 3. If it is not a bracket, compare the scanned operators with the operators at the top of the stack. If the scanned operator has a higher priority than the stack top operator, the operator is pushed to the stack. Otherwise, the operators in the stack pop-up will be added to the end of the array newExpressionStrs until the operator or stack with a lower priority than the scan is empty, and the scanned operator is pushed into the stack. In this way, scan sequentially until the end of the scan. If the scan is complete and there are still elements in the stack, the suffix expression is displayed and added to the end of the array newExpressionStrs.
* @ Param expressionStrs
* @ Return
*/
Public List ToSuffixExpression (char [] expressionStrs ){
// A new expression
List NewExpressionStrs = new ArrayList ();
MyStack MyStack = new MyStack ();
Try {
For (int I = 0; I <expressionStrs. length; I ++ ){
If ('= (expressionStrs [I]) {// if it is left parenthesis

MyStack. push (expressionStrs [I]);
} Else if ('+' = expressionStrs [I] | '-' = expressionStrs [I] | '*' = expressionStrs [I] | '/' = expressionStrs [I]) {

If (! MyStack. empty () {// retrieves the first-in-stack Operator
Character s = MyStack. pop ();
If (comparePrior (expressionStrs [I], s) {// if the stack value has a higher priority than the value to be imported into the stack, It is pushed into the stack.
MyStack. push (s );
} Else {// otherwise retrieve the value
NewExpressionStrs. add (s );
}
}

MyStack. push (expressionStrs [I]);
} Else if (')' = expressionStrs [I]) {// if it is ')', it goes out of the stack until it encounters '('
While (! MyStack. empty ()){
Char s = MyStack. pop ();
If (! ('= S )){
NewExpressionStrs. add (s );
} Else {
Break;
}
}
} Else {
NewExpressionStrs. add (expressionStrs [I]);
}
}
While (! MyStack. empty ()){
Char s = MyStack. pop ();
NewExpressionStrs. add (s );
}
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Return newExpressionStrs;
}

Public static void main (String [] args ){

String expressionStr = "5 + (4-5 + 1)-4 + (6-5 + 3) + 2 ";
// Split it into an array of expressions
Char [] expressionChrs = expressionStr. toCharArray ();

List NewExpressionStrs;
Try {
NewExpressionStrs = new ExpressConvert (). toSuffixExpression (expressionChrs );
Iterator Iter = newExpressionStrs. iterator ();
While (iter. hasNext ()){
System. out. print (iter. next ());
}
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

}
}


// Computing

Public class Test4 {




Public static void main (String [] args ){
MyStack MS = new MyStack ();
String str = "1 + (5-3) * 5/5 ";
Char chr [] = str. toCharArray ();
ExpressConvert ec = new ExpressConvert ();
List List = ec. toSuffixExpression (chr );
Iterator Iter = list. iterator ();
While (iter. hasNext ()){
Character c = iter. next ();
Try {
If (c = '+' | c = '-' | c = '*' | c = '/'){

Int a = Integer. parseInt (ms. pop (). toString ());
Int B = Integer. parseInt (ms. pop (). toString ());


Int n = 0;
Switch (c ){

Case '+': n = B + a; break;
Case '-': n = B-a; break;
Case '*': n = B * a; break;
Case '/': n = B/a; break;
}

Ms. push (n );
} Else {
Ms. push (c );
}

} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
System. out. println (ms. getSize ());
Try {
System. out. println (ms. pop ());
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}

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.