Level 0. 다항식 더하기
istringstream을 이용해 파싱하여 해결했다.
특별히 더 고민해 볼 것은 없는 문제 같다.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string makePoly(int x, int c)
{
if (x == 0)
return to_string(c);
else
return (x == 1 ? "" : to_string(x)) + "x" + (c == 0 ? "" : (" + " + to_string(c)));
}
string solution(string polynomial)
{
istringstream iss(polynomial);
string s;
int x = 0, c = 0;
while (iss >> s)
{
size_t length = s.length();
if (s == "+")
continue;
else if (s[length - 1] == 'x')
x += (length == 1) ? 1 : stoi(s.substr(0, length - 1));
else
c += stoi(s);
}
return makePoly(x, c);
}
'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글
Level 0. 소인수분해 (0) | 2023.02.07 |
---|---|
Level 0. 구슬을 나누는 경우의 수 (0) | 2023.02.06 |
Level 0. 분수의 덧셈 (0) | 2023.02.04 |
Level 0. 겹치는 선분의 길이 (0) | 2023.02.03 |
Level 0. 가까운 수 (0) | 2023.02.02 |