Develop

[프로그래머스] 더 크게 합치기 본문

개인 공부/프로그래머스

[프로그래머스] 더 크게 합치기

개발 기록 2024. 1. 12. 14:48

 

문제

 

 

내 풀이

class Solution {
    public int solution(int a, int b) {
        
        String num1 = a + "" + b;
        String num2 = b + "" + a;
        
        if(Integer.parseInt(num1) >= Integer.parseInt(num2)){
           return Integer.parseInt(num1);
        }
        else{
            return Integer.parseInt(num2);
        }
        
    }
}

 

 

다른 풀이1

class Solution {
    public int solution(int a, int b) {
        int answer = 0;
        int aLong = Integer.parseInt(""+a+b);
        int bLong = Integer.parseInt(""+b+a);
        answer = aLong > bLong ? aLong : bLong;

        return answer;
    }
}

 

느낀점

 

비슷하게 사용했지만

String으로 변환하여 더한 값을 바로 int형 변수에 넣고

삼항연산자를 써서 코드 길이를 확 줄이는 방법이 확실히 더 좋아보인다

 

answer = 대신 retrun 해서 바로 리턴해도 좋았을듯

 

간단한 비교는 삼항을 쓰도록 계속 의식적으로 생각해야겠다

 

다른 풀이2

class Solution {
    public int solution(int a, int b) {
        return Math.max(Integer.parseInt(a + "" + b), Integer.parseInt(b + "" + a));
    }
}

 

느낀점

int형에 넣은 다음 그냥 큰 값을 반환해주는 Math.max 함수를 쓰는 방법도 있음

알고있는 함수지만 사용을 못했음