https://school.programmers.co.kr/learn/courses/30/lessons/120863
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
나의 풀이
class Solution {
public String solution(String polynomial) {
String answer;
int coe = 0;
int con = 0;
String[] degree = polynomial.split(" \\+ ");
for (String d : degree) {
if (d.equals("x")) coe++;
else if (d.contains("x")) {
d = d.substring(0, d.length()-1);
coe += Integer.parseInt(d);
}
else {
con += Integer.parseInt(d);
}
}
if (con != 0) {
if (coe == 1) answer = "x + " + con;
else if(coe == 0) answer = "" + con;
else answer = coe + "x + " + con;
} else {
if (coe == 1) answer = "x";
else answer = coe + "x";
}
return answer;
}
}
다른 풀이
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" : "");
}
}