[알고리즘/프로그래머스] - 가장 큰 수(python)

유현민·2022년 6월 11일
0

알고리즘

목록 보기
206/253

문제

cmp_to_key를 사용해서 문제를 풀었다.

  1. compare함수를 만든다.
  2. [6, 10, 2]를 예로 들면

    6, 10이 문자이기 때문에
    a + b -> 610
    b + a -> 106
    두개를 비교하면 a + b가 더 크기 때문에 1을 반환한다.
    작으면 -1, 같으면 0을 반환

  3. 똑같은 방법으로 두개씩 계속 비교를 한다.
import functools


def compare(a, b):
    t1 = a + b
    t2 = b + a
    if t1 > t2:
        return 1
    elif t1 < t2:
        return -1
    else:
        return 0


def solution(numbers):
    if not sum(numbers):
        return '0'
    numbers = list(map(str, numbers))
    numbers = sorted(numbers, key=functools.cmp_to_key(compare), reverse=True)
    return ''.join(numbers)
profile
smilegate megaport infra

0개의 댓글