Playground/자바문제집

[프로그래머스] 다항식 더하기

미숫가루설탕많이 2023. 2. 7. 14:26
class Solution {
    public String solution(String polynomial) {
        int xCount = 0; int numCount = 0;

        for (String s : polynomial.split(" ")) {
            if (s.contains("x")) {
                xCount += s.equals("x") ? 1 : Integer.parseInt(s.replaceAll("x", ""));
            } else if (!s.equals("+")) {
                numCount += Integer.parseInt(s);
            }
        }
        
        return (xCount != 0 ? (xCount > 1 ? xCount + "x" : "x") : "") 
        		+ (numCount != 0 ? (xCount != 0 ? " + " : "") 
                + numCount : xCount == 0 ? "0" : "");
    }
}

'Playground > 자바문제집' 카테고리의 다른 글

[프로그래머스] 약수의 합  (0) 2023.02.07
[프로그래머스] 평행  (0) 2023.02.07
[프로그래머스] OX퀴즈  (0) 2023.02.06
[프로그래머스] 저주의 숫자 3  (0) 2023.02.06
[프로그래머스] 등수 매기기  (0) 2023.02.06