카테고리 없음

[프로그래머스] 다항식 더하기 (Java, Python)

garamdev 2026. 9. 4.
728x90

문제

https://school.programmers.co.kr/learn/courses/30/lessons/120863

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

코드(Java)

class Solution {
    public String solution(String polynomial) {
        int xNum = 0;
        int constant = 0;
        
        String[] terms = polynomial.split(" \\+ ");
        
        for (String term : terms) {
            if (term.contains("x")) {
                if (term.equals("x")) {
                    xNum += 1;
                } else {
                    xNum += Integer.parseInt(term.replace("x", ""));
                }
            } else {
                constant += Integer.parseInt(term);
            }
        }
        
        StringBuilder sb = new StringBuilder();
        if (xNum != 0) {
            if (xNum == 1) sb.append("x");
            else sb.append(xNum).append("x");
        }
        
        if (constant != 0) {
            if (sb.length() > 0) sb.append(" + ");
            sb.append(constant);
        }
        
        if (sb.length() == 0) return "0";
        
        return sb.toString();
    }
}

 

코드(Python)

def solution(polynomial):
    
    x_num = 0
    const = 0
    
    for term in polynomial.split(' + '):
        if 'x' in term:
            if term == 'x':
                x_num += 1
            else:
                x_num += int(term[:-1])
        else:
            const += int(term)
                
    answer = []
    if x_num != 0:
        if x_num == 1:
            answer.append('x')
        else:
            answer.append(f'{x_num}x')
            
    if const != 0:
        answer.append(str(const))
        
    return ' + '.join(answer)