题解 | #牛的表达式计算器#
牛的表达式计算器
https://www.nowcoder.com/practice/261e7f01438f414c92f59c0059d3a906
package main
import "strconv"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串一维数组
* @return int整型
*/
func calculatePostfix( tokens []string ) int {
// write code here
if len(tokens)==0{
return 0
}
stack :=&stack{}
for _,value :=range tokens{
switch value{
case "+":
num1 :=stack.top()
stack.pop()
num2 :=stack.top()
stack.pop()
stack.push(num1+num2)
case "-":
num1 :=stack.top()
stack.pop()
num2 :=stack.top()
stack.pop()
stack.push(num2-num1)
case "/":
num1 :=stack.top()
stack.pop()
num2 :=stack.top()
stack.pop()
stack.push(num2/num1)
case "*":
num1 :=stack.top()
stack.pop()
num2 :=stack.top()
stack.pop()
stack.push(num1*num2)
default :
num,_ :=strconv.Atoi(value)
stack.push(num)
}
}
return stack.top()
}
type stack struct{
intStack []int
}
func (s *stack) push(num int){
s.intStack = append(s.intStack, num)
}
func (s *stack) pop(){
if len(s.intStack)==0{
return
}
s.intStack=s.intStack[:len(s.intStack)-1]
}
func (s *stack) top()int{
if len(s.intStack)==0{
return 0
}
return s.intStack[len(s.intStack)-1]
}

