728x90
SMALL

class Solution {
    public String solution(String polynomial) { 
        String answer = "";
        int x_num = 0;
        int constant = 0;
        String[] words = polynomial.split("\\+");
        
        for( int i = 0 ; i < words.length ; i++ )
        {
            String word = words[i].trim();
            System.out.println( word );
            
            if( word.endsWith("x") )
            {
                if( word.length() == 1 ) x_num += 1;
                else x_num += Integer.parseInt( word.substring( 0, word.length() - 1 ) );
            }                                 
            else 
              constant += Integer.parseInt( word );
        }

        if ( x_num == 0 ) 
          answer = String.valueOf( constant );
        else if( constant == 0 ) 
        {
            if( x_num == 1 ) answer = "x";
            else answer = x_num + "x";
        }
        else if ( constant == 0 && x_num == 0 ) 
          answer = "0";
        else 
        {
            if( x_num == 1 ) answer = "x + " + constant;
            else answer =  x_num + "x + " + constant;
        }

        return answer;
    }
}

 

 

C#

 

using System;

public class Solution {
    public string solution(string polynomial) {
        string answer = "";
        string temp = "";
        string[] str = polynomial.Split(" ");
        int xNum = 0;
        int num = 0;
        
        for(int i = 0; i < str.Length; i+=2)
        {
            // Contains()을 활용해 str[i]에 x가 있는지 확인
            if(str[i].Contains("x"))
            {
                // temp에 str[i].Replace를 활용해 x를 string.Empty로 초기화
                temp = str[i].Replace("x", string.Empty);
                // temp에 값이 없으면 xNum에 1을 더함
                if(temp == "")
                {
                    xNum += 1;
                }
                // temp에 값이 있으면 xNum에 int형으로 변환후 더함
                else
                {
                    xNum += int.Parse(temp);
                }
            }
            else
            {
                num += int.Parse(str[i]);
            }
        }
        if(num == 0)
        {
            if(xNum == 1)
            {
                answer = "x";
            }
            else
            {
                answer = xNum.ToString() + "x";
            }
        }
        else
        {
            if(xNum == 0)
            {
                answer = num.ToString();
            }
            else if(xNum == 1)
            {
                answer = "x " + "+ " + num.ToString();
            }
            else
            {
                answer = xNum.ToString() + "x " + "+ " + num.ToString();
            }
        }
        return answer;
    }
}

728x90

설정

트랙백

댓글