Java/Coding Test

다항식 더하기 문제풀이

최고다최코딩 2023. 9. 17. 21:12
728x90

다항식이 문자열로 주어질 때 연산을 반환 

연산자는 '+'만 존재하고 1차항과 상수항만 주어진다.

 

public String solution(String polynomial) {

String answer = "";

String[] a = polynomial.split(" ");

int x = 0;

int y = 0;

for (int i = 0; i < a.length; i+=2) {

if(a[i].contains("x")) {

x+=Integer.parseInt((a[i].substring(0,a[i].length()-1).equals(""))?"1":a[i].substring(0,a[i].length()-1));

}

else y+=Integer.parseInt(a[i]);

}

return x == 0 ? y==0 ? "0" : y+"" : x==1 ? y==0 ? "x" : "x + "+y : y==0 ? x+"x" : x+"x + "+y;

}

1차항과 상수항을 따로 구하고 

0x 또는 1x, 0 등이 나오지 않게 걸러준다.