Go Implementation Calculator

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Only arithmetic, using stack structures and suffix expressions to calculate mathematical expressions, supports the use of () changing operator precedence.

This article code: GITHUB

Operating effect:

Problem

How do I programmatically calculate the value of a mathematical expression if we can only perform a subtraction of two values?

For example 1+2*3+(4*5+6)*7 , we know that the priority order is () greater than * / or greater than + - the direct calculation1+6+26*7 = 189


Calculation of infix and suffix expressions

People use infix expressions to calculate values

The notation of mathematical expressions is divided into prefix, infix and suffix notation, in which infix is the upper arithmetic notation: The value of the 1+2*3+(4*5+6)*7 infix expression is computed: the expression is divided into three parts to 1 2+3 (4*5+6)*7 calculate the value, summing 189. But the realization of this understanding process on the computer is complicated.

Computer calculates values using suffix expressions

1+2*3+(4*5+6)*7suffix expression corresponding to infix expression: 123*+45*6+7*+ The computer uses the stack to calculate the suffix expression value:

Code implementation for computing suffix expressions

 1  
2
3
4
5
6
7
8
9
10
11
12
13
Span class= ' line ' >14
15
16
17
18
19
20
21
22
23
24
25
26
27
  func calculate(postfix string) int  {
stack: = stack. itemstack{}
Fixlen: = len(postfix)
For i: = 0; i < Fixlen; i++ {
Nextchar: = string(Postfix[i])
//Digital: Direct Press Stack
if Unicode. IsDigit (Rune(Postfix[i])) {
stack. Push (Nextchar)
} Else {
//Operator: Take out two numerical values and press the result to stack
Num1, _: = StrConv. Atoi (Stack. Pop ())
num2, _: = StrConv. Atoi (Stack. Pop ())
Switch nextchar {
Case "+":
stack. Push (StrConv. Itoa (NUM1 + num2))
Case "-":
stack. Push (StrConv. Itoa (num1-num2))
Case "*":
stack. Push (StrConv. Itoa (NUM1 * num2))
Case "/":
stack. Push (StrConv. Itoa (num1/num2))
}
}
}
result, _: = StrConv. Atoi (Stack. Top ())
return result
}

Now just know how to convert infix to suffix, and then use the stack calculation.


Infix expression-to-suffix expression

Conversion process

The infix expression is traversed from left to right by character, and the output character sequence is a suffix expression:

Encountered digital Direct output

When the operator is encountered, it is judged:

    • Stack top operator priority is lower then stack, higher or equal direct output
    • Stack is empty, stack top is ( directly into the stack
    • Operator is ) to eject the top operator of the stack until it encounters)

Infix expression traversal completed, the operator stack is not empty all pop up, append to the output


Code implementation of the transformation

1
2
3
4
5
6
7
8
9
Ten
One
A
-
-
the
-
-
-
+
-
+
A
at
-
-
-
-
-
in
-
to
+
-
the
*
$
Panax Notoginseng
-
the
+
A
the
+
-
$
$
-
-
the
-
Wuyi
the
-
Wu
-
About
$
-
-
-
A
+
the
-
$
the
the
the
the
-
in
the
the
About
the
//infix expression-to-suffix expression
func infix2topostfix(exp string) string {
stack: = stack. itemstack{}
postfix: = ""
Explen: = len(exp)

//traverse the entire expression
For i: = 0; i < Explen; i++ {

Char: = string(Exp[i])

Switch char {
Case "":
Continue
Case "(":
///left parenthesis directly into the stack
stack. Push ("(")
Case ")":
//Right parenthesis pops the element until an opening parenthesis is encountered
For !stack. IsEmpty () {
Prechar: = stack. Top ()
if Prechar = = "(" {
stack. Pop () //Eject "("
Break
}
postfix + = Prechar
stack. Pop ()
}

//numbers are directly output
Case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
J: = i
digit: = ""
For ; j < Explen && Unicode. IsDigit (rune(exp[j)); J + + {
digit + = string(Exp[j])
}
postfix + = digit
i = J- 1 //I move forward across an integer, minus 1 due to a step of unnecessary J + +

default:
//Operator: A high-priority operator that pops up until a lower-priority operator is encountered
For !stack. IsEmpty () {
Top: = stack. Top ()
if top = = "(" | | Islower (top, char) {
Break
}
postfix + = Top
stack. Pop ()
}
///low-priority operators into the stack
stack. Push (char)
}
}

//Stack not empty then all output
For !stack. IsEmpty () {
postfix + = stack. Pop ()
}

return postfix
}

//comparison operation Fu top and new operator Newtop priority level
func islower(top string, Newtop string) bool {
//Note A + B + C suffix expression is AB + C +, not ABC + +
switch top {
Case "+", "-":
if newtop = = "*" | | newtop = = "/" {
return true
}
Case "(":
return true
}
return false
}


Summarize

The value of the

Computer computing mathematical expression is divided into 2 steps, using the stack to convert a person's infix expression to a computer-understood suffix expression, again using the stack to compute the value of the suffix expression.

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.