-
프로그래머스 - 다항식 더하기알고리즘 2024. 4. 5. 01:29
import java.util.*; class Solution { public String solution(String polynomial) { StringBuilder sb = new StringBuilder(); int var = 0; int con = 0; List<Integer> variables = new ArrayList<>(); List<Integer> constants = new ArrayList<>(); for(String s : polynomial.split(" ")) { if(s.contains("x")) { s = s.replace("x", ""); if(s.equals("")) variables.add(1); else variables.add(Integer.parseInt(s)); } else if(s.contains("+")) { continue; } else { constants.add(Integer.parseInt(s)); } } for(int n : variables) { var += n; } for(int n : constants) { con += n; } if(var == 1) sb.append("x"); else if(var != 0) sb.append(Integer.toString(var) + "x"); if(var != 0 && con != 0) sb.append(" + "); if(con != 0) sb.append(Integer.toString(con)); return sb.toString(); } }
x가 1일 때 1x가 아닌 x가 되어야 하며, 변수나 상수 값이 없다면 + 가 없어야 하므로 값을 체크해주어야 합니다.
'알고리즘' 카테고리의 다른 글
프로그래머스 - 최소 직사각형 (0) 2024.04.12 프로그래머스 - 시저 암호 (0) 2024.04.11 프로그래머스 - 최빈값 구하기 (1) 2024.04.06 프로그래머스 - 겹치는 선분의 길이 (0) 2024.04.06 프로그래머스 - 안전지대 (0) 2024.04.05