Post

[Programmers] #181938 - 두 수의 연산값 비교하기 [Java][C++][Python]

[Programmers] #181938 - 두 수의 연산값 비교하기 [Java][C++][Python]

문제 링크


1. 아이디어

양의 정수 a, b가 주어졌을 때, $a \oplus b$와 $2 \times a \times b$ 중에서 더 큰 값을 반환하는 문제다. $a \oplus b$는 두 수를 문자열로 변환해서 문자열 이어붙이기를 한 후 다시 정수로 형변환을 하면 간단하게 처리할 수 있으므로 이를 이용해 두 연산 결과 중 더 큰 값을 반환했다.


2. 복잡도

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

($A$ = a의 자릿수 $\approx \log_{10} a$, $B$ = b의 자릿수 $\approx \log_{10} b$)


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 = 2 * a * b;
        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 = 2 * a * b;
    return max(x, y);
}
1
2
3
4
def solution(a, b):
    x = int(f"{a}{b}")
    y = 2 * a * b
    return max(x, y)

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