Post

[Programmers] #181939 - 더 크게 합치기 [Java][C++][Python]

두 양의 정수를 이어붙이는 두 가지 순서 중 더 큰 값을 반환하는 워밍업 문제.

[Programmers] #181939 - 더 크게 합치기 [Java][C++][Python]

문제 링크


1. 아이디어

양의 정수 a, b를 이어붙이는 순서 $a \oplus b$와 $b \oplus a$ 중 더 큰 값을 반환하면 되는 문제다. a, b를 문자열로 바꿔 두 순서로 각각 이어붙인 뒤 다시 정수로 변환해 비교하면 된다. 두 값이 같을 때는 $a \oplus b$를 반환해야 하는데, 이 경우 두 값 자체가 동일하므로 최댓값을 구하는 연산이 자연스럽게 $a \oplus b$를 반환해 별도의 동점 처리가 필요 없다.


2. 복잡도

접근시간공간
풀이$O(1)$$O(1)$

3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
class Solution {
    public int solution(int a, int b) {
        int x = Integer.parseInt("" + a + b);
        int y = Integer.parseInt("" + b + a);
        return Math.max(x, y);
    }
}
1
2
3
4
5
6
7
8
#include <bits/stdc++.h>
using namespace std;

int solution(int a, int b) {
    int x = stoi(to_string(a) + to_string(b));
    int y = stoi(to_string(b) + to_string(a));
    return max(x, y);
}
1
2
3
4
def solution(a, b):
    x = int(f"{a}{b}")
    y = int(f"{b}{a}")
    return max(x, y)

This post is licensed under CC BY 4.0 by the author.