给定一个字符串形式的表达式 s ,请你实现一个计算器并返回结果,除法向下取整。
数据范围:表达式长度满足 ,字符串中包含 + , - , * , / , 保证表达式合法。
"1*10"
10
"8*9-19"
53
"100000*100*0"
0
"100000*100/9"
1111111
package main import _"fmt" import "strconv" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ func calculate( s string ) int { ints:=[]int{} symbols:=[]byte{} pre:="" for _,ch:=range []byte(s){ if ch=='-'||ch=='+'{ ints=append(ints,calc(pre)) symbols=append(symbols,ch) pre="" }else{ pre+=string(ch) } } ints=append(ints,calc(pre)) ans:=ints[0] for i,x:=range ints[1:]{ if symbols[i]=='-'{ ans-=x }else{ ans+=x } } return ans } func calc(s string)int{ ints:=[]int{} symbols:=[]byte{} pre:="" for _,ch:=range []byte(s){ if ch=='*'||ch=='/'{ x,_:=strconv.Atoi(pre) ints=append(ints,x) symbols=append(symbols,ch) pre="" }else{ pre+=string(ch) } } x,_:=strconv.Atoi(pre) ints=append(ints,x) ans:=ints[0] for i,x:=range ints[1:]{ if symbols[i]=='*'{ ans*=x }else{ ans/=x } } return ans }