You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# include <bits/stdc++.h>
using namespace std ;
// 2013NOIP普级组第二题- - 表达式的值( 参考洛谷题解)
// https://blog.csdn.net/u014542643/article/details/78435113
/*
栈( stack)
(1) 读入字符,当其为”+“时,我们先不管;当其为数时则入栈;当其为“*”时我们继续往后读一个数,再从栈中取出一个数与其相乘,将其乘积入栈;
(2) 第一项执行完毕后,我们将栈中的元素累加,再输出和。显然,这就是我们想要的答案。
*/
/**
* 功能:将字符串转为整数
* @param str
* @return
*/
int StrToInt ( string str ) {
istringstream stream1 ;
stream1 . str ( str ) ;
int i ;
stream1 > > i ;
return i ;
}
int main ( ) {
string x ;
getline ( cin , x ) ;
//字符串的长度
int len = x . length ( ) ;
//数字栈
stack < int > numStack ;
//操作符栈
stack < char > opStack ;
//遍历每一个字符
for ( int i = 0 ; i < len ; ) {
string s = " " ;
while ( x [ i ] > = ' 0 ' & & x [ i ] < = ' 9 ' ) {
s + = x [ i ] ;
i + + ;
}
//数字入栈
if ( s ! = " " ) {
numStack . push ( StrToInt ( s ) ) ;
if ( ! opStack . empty ( ) & & opStack . top ( ) = = ' * ' ) {
//如果发现在运算符栈中栈顶是*,那么需要把数字栈中两个数字拿出来,然后相乘再放回去
int a = numStack . top ( ) ;
numStack . pop ( ) ;
int b = numStack . top ( ) ;
numStack . pop ( ) ;
numStack . push ( a * b ) ;
//乘号出栈
opStack . pop ( ) ;
}
}
//操作符,这里只处理*即可。
if ( x [ i ] = = ' * ' ) {
opStack . push ( x [ i ] ) ;
}
//如果是+号,就不需要处理了,但不管是数字还是符号,都需要向后再走一个,好读取下一个。
i + + ;
}
// 将结果加在一起
int sum = 0 ;
while ( ! numStack . empty ( ) ) {
int a = numStack . top ( ) ;
numStack . pop ( ) ;
sum + = a ;
}
cout < < sum < < endl ;
return 0 ;
}