프로그래머스 문제풀이/Level 0

다항식 더하기 (자바, Java)

뮤츠 2022. 12. 11. 23:06

 

생각보다 까다로웠다.

x의 계수, 상수를 따로 나누어서 경우의 수를 구했다.

그래서 각각의 값이 0인경우를 나누어서 출력했는데...

x의 계수가 1인 경우, 1x로 출력하는 경우가 있었다.

그래서 그 경우까지 if로 잡아주고 해결.

 

class Solution {
    public String solution(String polynomial) {
    	
        String[] arr = polynomial.split(" ");
        int x = 0;
        int con = 0;
        for (int i=0; i<=arr.length/2; i++) {
        	String str = arr[2*i];
        	if (str.contains("x")) {
        		if (str.replace("x", "").equals("")) {
        			x+= 1;
        		} else {
        			x+= Integer.parseInt(str.replace("x", ""));
        		}        		
        	} else {
        		con+=Integer.parseInt(str);
        	}
        }
        StringBuilder sb = new StringBuilder();
        if (x==0) {
        	sb.append(con);
        } else if (con==0) {
        	if (x==1) {
        		sb.append("x");
        	} else {
        		sb.append(x).append("x");
        	}        	
        } else {
        	if (x==1) {
        		sb.append("x").append(" + ").append(con);
        	} else {
        		sb.append(x).append("x").append(" + ").append(con);
        	}        	
        }
        String answer = sb.toString();
        
        return answer;
    }
}