한 개 이상의 항의 합으로 이루어진 식을 다항식이라고 합니다.
다항식을 계산할 때는 동류항끼리 계산해 정리합니다.
덧셈으로 이루어진 다항식polynomial이 매개변수로 주어질 때,
동류항끼리 더한 결괏값을 문자열로return하도록solution함수를 완성해보세요.
같은 식이라면 가장 짧은 수식을return합니다.
public class PolynomialAdder
{
const char X = 'x';
const char PLUS = '+';
static int _xCoefficient = 0;
static int _constant = 0;
public static string Solution(string polynomial)
{
//각 항의 계수 초기화
_xCoefficient = 0;
_constant = 0;
var terms = polynomial.Split(PLUS);
foreach (var term in terms)
{
ParseTerm(term);
}
string answer = "";
if (_xCoefficient != 0)
{
answer = _xCoefficient == 1 ? "x" : $"{_xCoefficient}x";
if (_constant != 0)
answer += $" + {_constant}";
}
else
{
if (_constant != 0)
answer += $"{_constant}";
}
return answer;
}
private static void ParseTerm(string term)
{
term = term.Replace(" ", "");
if (term.Contains(X))
{
term = term.Replace(X.ToString(), "");
if (term == "")
_xCoefficient += 1;
else
_xCoefficient += int.Parse(term);
}
else
_constant += int.Parse(term);
}
}
+기호로만 이루어진 식이므로 PLUS = '+'를 기준으로 Split하여 +에 따라 분리된 string 배열로 구성 private static void ParseTerm(string term)
{
term = term.Replace(" ", "");
if (term.Contains(X))
{
term = term.Replace(X.ToString(), "");
if (term == "")
_xCoefficient += 1;
else
_xCoefficient += int.Parse(term);
}
else
_constant += int.Parse(term);
}
+로 분리된 식에서 x를 가진 1차 항이 있고 상수 항이 존재하므로 그에 따라 구분하여 처리하도록 함x가 포함되어 있을 때는 x를 제거했을 때 남는 정수를 x의 계수를 의미하는 _xCoefficient에 더하거나 공백일 경우 x만 있었던 경우이므로 1을 계수로 가지고 있었음을 확인해 1을 추가x가 포함되어 있지 않다면 상수항이므로 _constant에 해당 값을 추가 string answer = "";
if (_xCoefficient != 0)
{
answer = _xCoefficient == 1 ? "x" : $"{_xCoefficient}x";
if (_constant != 0)
answer += $" + {_constant}";
}
else
{
if (_constant != 0)
answer += $"{_constant}";
}
return answer;
_xCoefficient가 0이 아니라는 뜻은 1차항의 계수가 존재한다는 의미이므로 값이 1인지 확인해 1이라면 "x"를 최종 결과물에 추가하고 그렇지 않을 경우 계수를 앞에 추가한 "{_xCoefficient}x"를 추가answer를 구성