题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

package main

import (
	"fmt"
	"strconv"
)

var pos int

func main() {
	var s string
	fmt.Scan(&s)
	num := cal(s, len(s))
	fmt.Print(num)
}

func cal(s string, length int) int {
	var flag = '+'
	var stack []int
	var sum = 0
	var num = 0
	for pos < length {
		if s[pos] == '{' || s[pos] == '[' || s[pos] == '(' {
			pos++
			num = cal(s, length)
		}
		for pos < length && s[pos] >= '0' && s[pos] <= '9' {
			a, _ := strconv.Atoi(string(s[pos]))
			num = num*10 + a
			pos++
		}
		switch flag {
		case '+':
			stack = append(stack, num)
		case '-':
			stack = append(stack, -num)
		case '*':
			stack[len(stack)-1] = stack[len(stack)-1] * num
		case '/':
			stack[len(stack)-1] = stack[len(stack)-1] / num
		}
		num = 0
		if pos < length {
            flag = rune(s[pos])
			if flag == '}' || flag == ']' || flag == ')' {
                pos++
				break
			}
		}
		pos++
	}
	for i := 0; i < len(stack); i++ {
		sum += stack[i]
	}
	return sum
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务