package main
// 原文大佬:https://www.nowcoder.com/profile/4797221
import (
"strings"
)
func solve(s string) int {
// 括号用递归处理
// 加减乘除由于乘除优先级更高的特性,所以采用临时数组保存加减因子,加减因子上附加的乘除运算先进行
// 最后统计临时数组的所有加减因子之和
// 声明一个存放临时数据的数组
its := make([]int, 0)
// 下一个待入数组的数据的运算符,第一个为“+”
var operator byte = '+'
// 运算数字因子
tempNum := 0
// 字符串转数组
chars := []byte(s)
l := 0
for i := 0; i < len(chars); i++ {
c := chars[i]
// 0~9 字符是数字
if c >= '0' && c <= '9' {
tempNum = 10*tempNum + int(c-'0')
}
if '(' == c {
l++
start, end := i+1, i+1
for l != 0 {
if chars[end] == ')' {
l--
}
if chars[end] == '(' {
l++
}
end++
}
i = end - 1
tempNum = solve(s[start:end])
}
if strings.Contains("+-*/", string(c)) || i == len(chars)-1 {
switch operator {
case '+':
its = append(its, tempNum)
case '-':
its = append(its, -tempNum)
case '*':
its[len(its)-1] *= tempNum
case '/':
its[len(its)-1] /= tempNum
}
tempNum = 0
operator = c
}
}
result := 0
for _, el := range its {
result += el
}
return result}



京公网安备 11010502036488号