Post

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

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

문제 링크


1. 아이디어

$a \oplus b$는 두 수를 문자열로 이어 붙인 뒤 다시 정수로 읽은 값이다. 문제는 이 값과 2 * a * b 중 큰 쪽을 반환하는 것이다. 두 값이 같을 때 $a \oplus b$를 반환하라는 조건은 값이 같으면 어느 쪽을 반환해도 결과가 같으므로 max로 충분하다.


2. 코드

풀이 [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);
    }
}

"" + a + b처럼 빈 문자열에 먼저 붙여, 덧셈이 아니라 문자열 연결이 되게 했다.

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.