题解 | #逆波兰表达式求值#
逆波兰表达式求值
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 }