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

silver's avatar
Feb 04, 2025
[알고리즘문제풀기] 다항식 더하기

문제

내가 작성한 오답

• includeX == 0인 경우 answer = Integer.toString(num); → 만약 includeX == 0이고 num == 0이면, answer = "0"이 되어야 하지만, 문제에서 0은 주어지지 않으므로 필요 없는 처리임. • num == 0일 때 "1x"가 아닌 "x"로 변환하는 처리가 없음. → 예를 들어 includeX == 1이면 "1x"가 아니라 "x"여야 하는데 이를 고려하지 않음.
class Solution { public String solution(String polynomial) { String answer = ""; String[] poly = polynomial.split(" "); int includeX = 0; int num = 0; for(int i = 0; i < poly.length; i+=2){ if(poly[i].contains("x")){ String a = poly[i].replace("x",""); includeX += a.isEmpty() ? 1 : Integer.parseInt(a); } else { num += Integer.parseInt(poly[i]); } } if(includeX==0){ answer = Integer.toString(num); } else { if(num==0){ answer = Integer.toString(includeX)+"x"; }else { answer = Integer.toString(includeX)+"x + "+Integer.toString(num); } } return answer; } }

내가 작성한 정답

class Solution { public String solution(String polynomial) { String answer = ""; String[] poly = polynomial.split(" "); int includeX = 0; int num = 0; for(int i = 0; i < poly.length; i+=2){ if(poly[i].contains("x")){ String a = poly[i].replace("x",""); includeX += a.isEmpty() ? 1 : Integer.parseInt(a); } else { num += Integer.parseInt(poly[i]); } } StringBuilder result = new StringBuilder(); if (includeX > 0) { result.append(includeX == 1 ? "x" : includeX + "x") } if (num > 0) { if (result.length() > 0) { result.append(" + "); } result.append(num); } return result.toString(); } }

다른 사람들의 정답

class Solution { public String solution(String polynomial) { int xCount = 0; // x의 계수를 저장할 변수 int num = 0; // 정수 부분을 저장할 변수 // 입력된 다항식을 공백으로 나누어 각 항을 처리 for (String s : polynomial.split(" ")) { if (s.contains("x")) { // 현재 항이 x를 포함하는 경우 // 'x'만 있는 경우에는 1을 더하고, 계수가 있는 경우에는 그 계수를 더함 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" : "") + // x의 계수 처리 (num != 0 ? (xCount != 0 ? " + " : "") + num : xCount == 0 ? "0" : ""); // 정수 부분 처리 } }
Share article

silver