[알고리즘문제풀기] 다항식 더하기

silver's avatar
Jan 15, 2026
[알고리즘문제풀기] 다항식 더하기

문제

내가 작성한 정답

class Solution { public String solution(String polynomial) { int x = 0, c = 0; for(String s:polynomial.split(" ")){ if(s.contains("x")) { String ss = s.replace("x", ""); x += ss.isEmpty()?1:Integer.parseInt(ss); } else if(s.equals("+")) continue; else c += Integer.parseInt(s); } if(x==0) return c+""; else if(x==1) return c==0?"x":"x + "+c; else return c==0? x+"x":x+"x + "+c; } }

다른 사람들의 정답

class Solution { public String solution(String polynomial) { int xCount = 0; int num = 0; for (String s : polynomial.split(" ")) { if (s.contains("x")) { xCount += s.equals("x") ? 1 : Integer.parseInt(s.replaceAll("x", "")); } else if (!s.equals("+")) { num += Integer.parseInt(s); } } return (xCount != 0 ? xCount > 1 ? xCount + "x" : "x" : "") + (num != 0 ? (xCount != 0 ? " + " : "") + num : xCount == 0 ? "0" : ""); } import java.util.StringTokenizer; class Solution { public String solution(String polynomial) { StringTokenizer st = new StringTokenizer(polynomial, " + "); StringBuilder sb = new StringBuilder(); int xsum = 0; int sum = 0; while (st.hasMoreTokens()) { String str = st.nextToken(); if (str.contains("x")) { String x = str.replace("x", ""); System.out.println(x); if (x.isBlank()) { xsum += 1; } else { xsum += Integer.parseInt(x); } } else { sum += Integer.parseInt(str); } } if (xsum == 0) { sb.append(sum); } else if (sum == 0) { if (xsum == 1) { sb.append("x"); } else { sb.append(xsum).append("x"); } } else { if (xsum == 1) { sb.append("x").append(" + ").append(sum); } else { sb.append(xsum).append("x").append(" + ").append(sum); } } return sb.toString(); } }
Share article

silver