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

Benjamin·2023년 2월 10일
0

프로그래머스

목록 보기
19/58


내 풀이

class Solution {
    public String solution(String polynomial) {
        String answer = "";
        int num = 0;
        int var = 0;
        String[] temp = polynomial.split(" ");
        for(int i=0; i<temp.length; i+=2) {
            if(temp[i].contains("x")) {
                if(temp[i].length() != 1) var += Integer.parseInt(temp[i].substring(0, temp[i].length() - 1)); // 헤맨부분 1
                else var++;
            } else {
                num += Integer.parseInt(temp[i]);
            }
        }
        String numStr = num >0 ? String.valueOf(num) : ""; // 헤맨부분2
        String varStr = var>0 ? var == 1 ? "x" : var+"x" : ""; // 헤맨부분2
        if(varStr.equals("")) {
            answer = numStr;
        } 
        else if(numStr.equals("")) {
            answer = varStr;
        }
        else answer = varStr + " + " + numStr;
        return answer;
    }
}

두 군데에서 해맸다.

Troubleshooting

원인 1
우선 x의 계수가 무조건 0~9까지로 한자리수일거라는 생각을 잘못했다.
그래서 헤맨부분1을 처음에는 if(temp[i].length() == 2) var += temp[0]-'0';로 썼다가 몇몇 테스트케이스에서 틀리는 일이 발생했다.

계수가 두자리 수 이상일 수 있기때문에, 조건문을 == 2 -> != 1 로 고치고,
temp[0]-'0'을 해서 한 자리수의 숫자를 구하는 대신, substring()을 활용해 맨 끝 x만 빼고 모두 숫자로 바꾸는 방식으로 수정했다.

Troubleshooting 2

원인 2
x가 있는 변수의 계수든 상수든 0일경우 해당 항은 아무것도 출력되지않도록 해야하고, x의 계수가 1일경우에 1은 출력되지않도록해야하는데, 이런 부분의 조건문을 조금 더럽게 짰었다.

삼항연산자를 이용해 두 줄로 코드를 수정했다.
1. 아무것도 출력되지않도록하기위해, ""을 한다는것을 생각못했다.
2. 삼항연산자가 여러개 중첩되는게 익숙하지않았다.
x > 0 ? y == 1 ? y식 관련 true: y식 관련 false : x식 관련 false이렇게 중첩해서 사용할수도있다.
그렇다면 여기서 y == 1 ? y관련 true: y관련 false는 x식 관련 true이다.

다른 풀이

public class PolynomialAddition {
	public String solution(String polynomial) {
		int coef = 0;   // 계수
		int cons = 0;   // 상수
		for (String p : polynomial.split(" ")) {
			if (p.contains("x")) coef += p.equals("x") ? 1 : Integer.parseInt(p.substring(0, p.length() - 1));
			else if (!p.equals("+")) cons += Integer.parseInt(p);
		}
		String coefStr = coef > 0 ? coef == 1 ? "x" : coef + "x" : "";
		String consStr = cons > 0 ? String.valueOf(cons) : "";
		String result = "";
		if (coef > 0) {
			if (cons > 0) result += coefStr + " + " + consStr;
			else result += coefStr;
		}
		else if (cons > 0) result += consStr;
		return result;
	}

	public static void main(String[] args) {
		PolynomialAddition polynomialAddition = new PolynomialAddition();
		System.out.println(polynomialAddition.solution("3x + 7 + x"));  // 4x + 7
		System.out.println(polynomialAddition.solution("x + x + x"));  // 3x
	}
}

0개의 댓글