题解 | #逆波兰表达式求值#

逆波兰表达式求值

https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

package main

import (
	// "fmt"
	"strconv"
)

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param tokens string字符串一维数组
 * @return int整型
 */
func evalRPN(tokens []string) int {
	// write code here
	arr := make([]string, 0)
	m := 0
	n := 0
	temp, _ := strconv.Atoi(tokens[0])
	for i := 0; i < len(tokens); i++ {
		switch tokens[i] {
		case "+":
			{
				m, _ = strconv.Atoi(arr[len(arr)-2])
				n, _ = strconv.Atoi(arr[len(arr)-1])
				temp = m + n
                arr = arr[:len(arr) - 2]
				arr = append(arr, strconv.Itoa(temp))
			}

		case "-":
			{
				m, _ = strconv.Atoi(arr[len(arr)-2])
				n, _ = strconv.Atoi(arr[len(arr)-1])
				temp = m - n
                arr = arr[:len(arr) - 2]
				arr = append(arr, strconv.Itoa(temp))
			}
		case "*":
			{
				m, _ = strconv.Atoi(arr[len(arr)-2])
				n, _ = strconv.Atoi(arr[len(arr)-1])
				temp = m * n
                arr = arr[:len(arr) - 2]
				arr = append(arr, strconv.Itoa(temp))
			}
		case "/":
			{
				m, _ = strconv.Atoi(arr[len(arr)-2])
				n, _ = strconv.Atoi(arr[len(arr)-1])
				temp = m / n
                arr = arr[:len(arr) - 2]
				arr = append(arr, strconv.Itoa(temp))
			}
		default:
			{
                arr = append(arr, tokens[i])
            }
		}
	}
    return temp
}

全部评论

相关推荐

ming_ri:“很抱歉,您的简历和我们当前的职位需求不是很匹配”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务