반응형
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
- 문제
다항식이 주어지면 해당 다항식을 정리하는 문제다.
- 풀이
#include <string>
#include <vector>
#include <sstream>
using namespace std;
string solution(string polynomial) {
string answer = "";
stringstream ss(polynomial);
int x = 0, dig = 0;
vector<string> s = {};
string temp;
while(ss >> temp)
s.push_back(temp);
for(auto a : s){
if(a.find('x') != string::npos){
a.erase(a.begin() + a.find('x'));
if(a.empty())
x += 1;
else
x += stoi(a);
}
else if(isdigit(a[a.size()-1]) != 0){
dig += stoi(a);
}
}
if(x > 0){
if(x == 1)
answer += "x";
else
answer += (to_string(x) + "x");
if(dig > 0){
answer += (" + " + to_string(dig));
}
}
else if( x == 0){
if(dig > 0)
answer += to_string(dig);
// else
// answer += "0";
}
return answer;
}
1x일때 1x가 아니라 x로 출력해야하는 부분때문에 오래 헤맸었다.
x가 나오게 만들어야 한다는 걸 주의할 것!
- 기억할 것!
X
반응형
'Algorithm > 프로그래머스' 카테고리의 다른 글
프로그래머스 중복된 숫자 개수 C++ (0) | 2024.08.19 |
---|---|
프로그래머스 카펫 C++ (0) | 2022.10.23 |
프로그래머스 다음 큰 숫자 C++ (0) | 2022.10.23 |
프로그래머스 주식가격 C++ (0) | 2022.10.22 |
프로그래머스 타겟 넘버 C++ (0) | 2022.10.22 |