코딩테스트/lv0

[프로그래머스 코딩테스트] java Lv.0 다항식 더하기

chantleman 2024. 8. 22. 09:49

 

    class Solution {
        public String solution(String polynomial) {
            String answer = "";

            int x=0;
            int num=0;

            String tokens[] = polynomial.split("\\+");
            for(String token:tokens)
            {
                token = token.trim();

                if(token.contains("x"))
                {
                    token = token.replace("x","");
                    if(token.equals("")) x++;
                    else x+=Integer.parseInt(token);
                }
                else{
                    num+=Integer.parseInt(token);
                }
            }
            String strX = "";
            if(x==0)  return num+"";
            else if(x==1) strX="x";
            else strX = x+"x";

            if(num==0) return strX;
            else return strX+" + "+num;
        }
    }