Skip to content

Commit

Permalink
이슈 #386에서 솔루션 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
actions-user committed Nov 26, 2024
1 parent b2146d0 commit 81e71b6
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Programmers/다항식_더하기.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include <string>
#include <vector>
#include <sstream>
#include <iostream>

using namespace std;

bool isLinear(string str) {
for (char c : str) {
if (c == 'x') {
return true;
}
}

return false;
}

int getNumber(string str) {
int result = 0;

for (char c : str) {
if (isdigit(c)) {
result = result * 10 + (c - '0');
}
}

return result;
}

string solution(string polynomial) {
int linear = 0;
int num = 0;
string code;
stringstream ss(polynomial);
while (ss >> code) {
if (code != "+") {
if (isLinear(code)) {
linear += getNumber(code);
if (code.length() == 1) {
linear++;
}
} else {
num += getNumber(code);
}
}
}

string linearStr = "";
if (linear == 1) {
linearStr = "x";
} else {
linearStr = to_string(linear) + "x";
}

if (linear != 0 && num != 0) {
return linearStr + " + " + to_string(num);
} else if (linear != 0) {
return linearStr;
} else {
return to_string(num);
}
}

0 comments on commit 81e71b6

Please sign in to comment.