Golang Implementation Calculator

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

Only basic arithmetic are used, and the values of mathematical expressions are computed using the stack structure and suffix expressions.
This code: GITHUB Original: Wuyin.io reprint please indicate the source.
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

func calculate(postfix string) int {    stack := stack.ItemStack{}    fixLen := len(postfix)    for i := 0; i < fixLen; i++ {        nextChar := string(postfix[i])        // 数字:直接压栈        if unicode.IsDigit(rune(postfix[i])) {            stack.Push(nextChar)        } else {            // 操作符:取出两个数字计算值,再将结果压栈            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

Infix expression-to-suffix expression func infix2topostfix (exp String) string {stack: = stack. itemstack{} postfix: = "" "Explen: = Len (exp)//traverse entire expression for I: = 0; i < Explen;            i++ {char: = string (exp[i]) switch char {case ': Continue Case ' (": The left parenthesis directly into the stack stack. Push (") case")://Right parenthesis pops the element until it encounters an opening parenthesis for!stack. IsEmpty () {prechar: = stack. Top () if Prechar = = "(" {stack. Pop ()//Eject "(" break} postfix + = Prechar stack.            Pop ()}//number directly outputs 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 forward across an integer, by     To perform an extra step of J + +, you need to subtract 1 default:       Operator: encounters a high-priority operators that pop up until a lower-priority operator for!stack is encountered. IsEmpty () {top: = stack. Top () if top = = "(" | | Islower (top, char) {break} Postfix + = Top stack. Pop ()}//Low-priority operators enter the stack stack. Push (char)}}//stack is not empty then all output for!stack. IsEmpty () {postfix + = stack. Pop ()} return postfix}//comparison operation Fu top and new operator Newtop Precedence high-low 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 computing mathematical expression of computer is divided into 2 steps, using stack to convert the infix expression of human understanding to the suffix expression of computer understanding, again using stack to compute the value of 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.