题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
package main import ( "os" "bufio" "fmt" "strconv" "strings" ) type Stake struct{ con []string } func (thisS *Stake)push(s string){ thisS.con = append(thisS.con, s) } func (thisS *Stake)pop()(s string){ s = thisS.con[len(thisS.con)-1] thisS.con = thisS.con[:len(thisS.con)-1] return } func main(){ input:=bufio.NewScanner(os.Stdin) input.Scan() data:=input.Text() d:=strings.Split(data,"") youxianji:=map[string]int{ "*":3,"/":3,"+":2,"-":2,"(":1,"{":1,"[":1, } //先搞个栈,这里因为只要压入删除功能,所以简单一点 var s Stake s.con = make([]string,0) //准备个字符切片用来放字符,因为有多位数,所以要切片 houzhui:=make([]string,0) lend:=len(d) for i:=0;i<lend;i++{ if (d[i]>="0"&&d[i]<="9")||(i>0&&d[i]=="-"&&(d[i-1]>"9"||d[i-1]<"0")&&d[i-1]!="}"&&d[i-1]!="]"&&d[i-1]!=")"){ str := d[i] if i!=lend-1{ i++ for d[i]>="0"&&d[i]<="9"&&i!=lend-1{ str = str + d[i] i++ } i-- } houzhui = append(houzhui,str) }else if d[i]=="("||d[i]=="["||d[i]=="{"{ s.push(d[i]) }else if d[i]=="}"||d[i]=="]"||d[i]==")"{ now := s.pop() for now!="("&&now!="["&&now!="{"{ houzhui = append(houzhui,now) now =s.pop() } }else { for len(s.con)!=0&&youxianji[d[i]]<=youxianji[s.con[len(s.con)-1]]{ houzhui = append(houzhui,s.pop()) } s.push(d[i]) } } for len(s.con)!=0{ houzhui = append(houzhui,s.pop()) } //后缀表达式搞完了,接着搞答案 //搞两个栈放数和运算符号,放进去 signzhan := Stake{} signzhan.con = make([]string,0) numzhan := Stake{} numzhan.con = make([]string,0) for _,i:=range houzhui{ if i!="+"&&i!="-"&&i!="*"&&i!="/"{ numzhan.push(i) }else { num2 := numzhan.pop() num1:=numzhan.pop() n1,_:=strconv.Atoi(num1) n2,_:=strconv.Atoi(num2) switch i { case "+":numzhan.push(strconv.Itoa(n1+n2)) case "-":numzhan.push(strconv.Itoa(n1-n2)) case "*":numzhan.push(strconv.Itoa(n1*n2)) case "/":numzhan.push(strconv.Itoa(n1/n2)) } } } fmt.Println(numzhan.pop()) }