x항과 숫자가 덧셈형식 문자열로 들어오면, x는 x끼리, 숫자는 숫자끼리 더해 문제열로 return 해주는 문제.
" + "를 split()으로 쪼개 String[]로 넣어주고 x항, 숫자 각각 더해주면 된다. 이 문제에서 성가셨던 부분은, x는 1x로 주어지지 않아 x항의 숫자부분을 따로 더해줄 때 오류가 생길 수 있다는 점이었다. 따라서 x의 앞이 1인 경우를 따로 뺀 후 최종적으로 더해주는 방식으로 구현했다.
class Solution {
public String solution(String polynomial) {
String answer = "";
String[] arr = polynomial.split(" +");
int linear = 0; //x를 count해줄 변수
int constant = 0; //숫자를 count해줄 변수
for (String s : arr) {
if (s.equals("x")) { //원소가 x일경우 linear++
linear += 1;
//원소가 x를 포함할 경우, x 제외 앞을 linear에 더해준다
} else if (s.contains("x")) {
linear += Integer.parseInt(s.substring(0, s.length() - 1));
} else if (!s.equals("+")) { //나머지들은 constant로 넣어준다
constant += Integer.parseInt(s);
}
}
if (linear != 0 && constant == 0) { //x항만 있고 숫자 없는경우
if (linear == 1) {
answer += "x";
} else {
answer += linear + "x";
}
}
if (linear != 0 && constant != 0) {
if (linear == 1) {
answer += "x" + " + " + constant;
} else {
answer += linear + "x" + " + " + constant;
}
}
if (linear == 0 && constant != 0) { //숫자만 있는경우
answer += constant;
}
return answer;
}
}