这一题基本思路就是模拟,如果想出来了几乎没什么难度。字符串用C++
自带的string类
就可以,非常方便。注意题目说可能有多余的空格,因此在输入后还要再转换到一个新的字符串里面。
代码中我多次用到了一个函数stoi
,从C++11
才支持,因此在NOIp中不可以使用。我在这里自己写了一个stoi2
,供大家参考。
int stoi2(string str) // 支持负数
{
int f = 1;
if (str[0] == '-')
f = -1, str = str.substr(1);
int x = 0;
for (size_t i = 0; i < str.length(); i++)
x = (x << 1) + (x << 3) + (str[i] ^ 48);
return x * f;
}
其实就是快读
主程序代码:
#include <iostream>
#include <string>
using namespace std;
int stoi2(string str) // 支持负数
{
int f = 1;
if (str[0] == '-')
f = -1, str = str.substr(1);
int x = 0;
for (size_t i = 0; i < str.length(); i++)
x = (x << 1) + (x << 3) + (str[i] ^ 48);
return x * f;
}
int main()
{
string str;
getline(cin, str);
string newstr;
for (const auto& c : str)
if (c != ' ')
newstr.push_back(c);
size_t posq = newstr.find('?'), posp = newstr.find('+'), posj = newstr.find('-'), pose = newstr.find('=');
int ans;
if (posq > pose)
if (posp != string::npos)
ans = stoi(newstr.substr(0, posp)) + stoi(string(newstr.begin() + posp + 1, newstr.begin() + pose));
else
ans = stoi(newstr.substr(0, posj)) - stoi(string(newstr.begin() + posj + 1, newstr.begin() + pose));
else if (posp != string::npos)
if (posp > posq)
ans = stoi(newstr.substr(pose + 1)) - stoi(string(newstr.begin() + posp + 1, newstr.begin() + pose));
else
ans = stoi(newstr.substr(pose + 1)) - stoi(newstr.substr(0, posp));
else
if (posj > posq)
ans = stoi(string(newstr.begin() + posj + 1, newstr.begin() + pose)) + stoi(newstr.substr(pose + 1));
else
ans = stoi(newstr.substr(0, posj)) - stoi(newstr.substr(pose + 1));
cout << ans << endl;
return 0;
}