使用计算机求算术的方法

题解

使用计算机求算术的方法

代码

#include <iostream>
#include <stack>
#include <map>
#include <cstring>
using namespace std;
stack<int>num;
stack<char>sign;
map<char, int>priority;
char s[1000009];
inline void gaochushuzi(char* s, int &lenth, int &return_num)
{
lenth = 0;
int signal = 1;
const char *p = s;
int tmp = 0;
if (*p == '-')
{
signal = -1;
p++;
lenth++;
}
while (1)
{
if (*p >= '0' && *p <= '9')
{
tmp = tmp * 10 + (*p - '0');
p++;
lenth++;
}
else
{
return_num = tmp * signal;
return;
}
}
}
int main()
{
priority['+'] = 0;
priority['-'] = 0;
priority['*'] = 1;
cin >> s;
int lenth = 0;
lenth = strlen(s);
for (int i = 0; i < lenth; )
{
{
int lenth;
int ret;
gaochushuzi(s + i, lenth, ret);
num.push(ret);
i += lenth;
}
if (sign.empty())//如果符号位为空,那么push符号
{
if (s[i] == 0)
{
cout << num.top()%10000 << endl;
return 0;
}
sign.push(s[i]);
i++;
}
else
{
int tmp = s[i];
{
if (tmp == 0)//表示结束
{
while(num.size()!=1)
{//计算
int ans = 0;
int b = num.top();
num.pop();
int a = num.top();
num.pop();
char op = sign.top();
sign.pop();
switch (op)
{
case '+':
ans = a + b;
break;
case '-':
ans = a - b;
break;
case '*':
ans = a * b;
break;
}
ans %= 10000;
num.push(ans);
}
cout << num.top() << endl;
return 0;
}
}
if (priority[tmp] > priority[ sign.top()])
{
sign.push(tmp);
i++;
}
else
{
while (sign.size() != 0 && priority[tmp] <= priority[sign.top()])
{
{//计算
int ans = 0;
int b = num.top();
num.pop();
int a = num.top();
num.pop();
char op = sign.top();
sign.pop();
switch (op)
{
case '+':
ans = a + b;
break;
case '-':
ans = a - b;
break;
case '*':
ans = a * b;
break;
}
ans %= 10000;
num.push(ans);
}
}
sign.push(tmp);
i++;
}
}
}
return 0;
}

image-20220104173542624

posted @   心坚石穿  阅读(76)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示