※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※
이번에 볼 문제는 백준 26577번 문제인 Math이다.
문제는 아래 링크를 확인하자.
https://www.acmicpc.net/problem/26577
26577번: Math
The first line will contain a single integer n that indicates the number of data sets that follow. Each data set will consist of a single line containing alternating integers and operators. There will be a space between each number and operator, and the on
www.acmicpc.net
주어지는 수식의 값을 계산해 문제를 해결하자.
괄호는 주어지지 않으므로, 곱하기와 나누기는 입력을 받으면서 처리하고 한 테스트케이스가 끝날 때 더하기와 빼기를 계산하는 식으로 구현해 문제를 해결하면 된다.
아래는 제출한 소스코드이다.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef long long ll;
string s;
vector<ll> nums;
vector<char> opers;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> s;
while (cin >> s) {
if ('0' <= s.back() && s.back() <= '9') {
ll cur = stoi(s);
if (nums.size() > opers.size()) {
ll ret = nums.front();
int opersize = opers.size();
for (int i = 0; i < opersize; i++) {
if (opers[i] == '+') ret += nums[i + 1];
else ret -= nums[i + 1];
}
cout << ret << '\n';
nums.clear(), opers.clear();
}
nums.emplace_back(cur);
}
else {
if (s == "*") {
ll nxt; cin >> nxt;
nums.back() *= nxt;
}
else if (s == "/") {
ll nxt; cin >> nxt;
nums.back() /= nxt;
}
else opers.emplace_back(s[0]);
}
}
ll ret = nums.front();
int opersize = opers.size();
for (int i = 0; i < opersize; i++) {
if (opers[i] == '+') ret += nums[i + 1];
else ret -= nums[i + 1];
}
cout << ret << '\n';
}
728x90
'BOJ' 카테고리의 다른 글
[BOJ 24452 // C++] 交易計画 (Trade Plan) (0) | 2022.12.21 |
---|---|
[BOJ 26548 // C++] Quadratics (0) | 2022.12.21 |
[BOJ 26576 // C++] Date (0) | 2022.12.20 |
[BOJ 24451 // C++] 飴 2 (Candies 2) (0) | 2022.12.20 |
[BOJ 6888 // C++] Terms of Office (0) | 2022.12.20 |