1180: [NOIP2013普及組]表達式求值

1180: [NOIP2013普及組]表達式求值
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 162 Solved: 71
[Submit][Status][Web Board]
Description
給定一個只包含加法和乘法的算術表達式,請你編程計算表達式的值。
Input
輸入僅有一行,爲需要你計算的表達式,表達式中只包含數字、加法運算符“+”和乘法運算符“*”,且沒有括號
,所有參與運算的數字均爲0到2^31-1之間的整數。輸入數據保證這一行只有0~ 9、+、*這12種字符。
0≤表達式中加法運算符和乘法運算符的總數≤100000
Output
輸出只有一行,包含一個整數,表示這個表達式的值。
注意:當答案長度多於4位時,請只輸出最後4位,前導0不輸出。
Sample Input

1+1*3+4 

Sample Output

8

HINT
請只輸出最後4位,前導0不輸出所以要取餘10000;
然後多組輸入用Ctrl+Z退出
Code:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<string>
#include<stdlib.h>
#include<stack>
using namespace std;
int main()
{
    stack<int>x;
    int n;
    char u;
    scanf("%d",&n);
    x.push(n);
    while(cin>>u>>n)
    {
        if(u=='+')
            x.push(n);
        else
        {
            int v=x.top();
            x.pop();
            x.push(n*v%10000);
        }
        //printf("1");
    }
    //cout<<2;
    int ans=0;
    while(!x.empty())
    {
        ans+=x.top();
        ans%=10000;
        //printf("%d\n",x.top());
        x.pop();
    }
    printf("%d\n",ans);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章