1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| public static double calculate(String s)
{
int len=s.length();
char[] str=s.toCharArray();
Stack<Integer> st_num=new Stack<>();
char op='#';
int ans=0,sign=1;
for(int i=0;i<len;i++){
if(str[i]==' ') continue;
if(str[i]>='0'&&str[i]<='9'){
int num=str[i]-'0';
while(i<len-1&&str[i+1]>='0'&&str[i+1]<='9')
num=num*10+(str[++i]-'0');
if(op!='#'){
if(op=='*')num*=st_num.pop();
else num=st_num.pop()/num;
op='#';
}
st_num.push(num);
}
else if(str[i]=='*'||str[i]=='/') op=str[i];
else{
ans+=st_num.pop()*sign;
sign=str[i]=='+'?1:-1;
}
}
return ans+st_num.pop()*sign;
}
|