题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
package main import ( "fmt" "strconv" ) func isGEPriority(op1 byte, op2 byte) bool { // 判断运算符 op1 的优先级是否大于等于 op2 if op1 == '(' { return false } if (op1 == '+' || op1 == '-') && (op2 == '*' || op2 == '/') { return false } return true } func operate(stk1 []int, stk2 []byte) ([]int, []byte) { // 计算操作,并把结果压入栈中 a, b := stk1[len(stk1)-2], stk1[len(stk1)-1] stk1 = stk1[:len(stk1)-2] op := stk2[len(stk2)-1] stk2 = stk2[:len(stk2)-1] var ans int if op == '+' { ans = a + b } if op == '-' { ans = a - b } if op == '*' { ans = a * b } if op == '/' { ans = a / b } stk1 = append(stk1, ans) return stk1, stk2 } func calculate(s string) int { var stk1 []int var stk2 []byte // 由于无法区分减号和负号,这里用一个标志位来进行区分 isOp := false for i:=0; i<len(s); i++ { if s[i] == '(' { stk2 = append(stk2, '(') } else if s[i] == ')' { for stk2[len(stk2)-1] != '(' { stk1, stk2 = operate(stk1, stk2) } // 弹出左括号 stk2 = stk2[:len(stk2)-1] } else if (isOp) { for isGEPriority(stk2[len(stk2)-1], s[i]) { stk1, stk2 = operate(stk1, stk2) } // 操作符入栈 stk2 = append(stk2, s[i]) isOp = false } else { start := i if s[i] == '+' || s[i] == '-' { i++ } for '0' <= s[i] && s[i] <= '9' { i++ } num, _ := strconv.Atoi(s[start:i]) stk1 = append(stk1, num) i-- isOp = true } } return stk1[len(stk1)-1] } func main() { var s string fmt.Scan(&s) s = "(" + s + ")" fmt.Println(calculate(s)) }
// 本题输入一行字符串,所以采用:fmt.Scan(&s)