반갑습니다!

[프로그래머스] 가장 큰 수 본문

알고리즘 문제 풀이

[프로그래머스] 가장 큰 수

김덜덜이 2020. 9. 7. 22:51
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr

풀이

해당 문제는 숫자를 문자열로 변환한 뒤, 문자열끼리 합친 결과를 비교하는 방법으로 쉽게 해결할 수 있는 문제이다.

코드

C++

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

bool comp(const string& a, const string& b) {
    return a + b > b + a;
}

string solution(vector<int> numbers) {
    string answer = "";
    bool is_all_zero = true; // 모든 숫자가 0인지 체크하기 위한 변수
    vector<string> nums; // 문자열로 변환한 숫자를 담을 벡터

    // 모든 숫자를 문자열로 변경
    for (int num : numbers) {
        nums.push_back(to_string(num));
        if (num != 0) is_all_zero = false;
    }
    if (is_all_zero) return "0"; // 모든 숫자가 0이면 정답도 0이 된다

    sort(nums.begin(), nums.end(), comp);

    for (string num : nums) answer += num;
    return answer;
}

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Solution {
    public String solution(int[] numbers) {
        String answer = "";
        boolean isAllZero = true; // 모든 숫자가 0인지 체크하기 위한 변수
        ArrayList<String> arr = new ArrayList<>(); // 문자열로 변환한 숫자를 담을 배열

        // 모든 숫자를 문자열로 변환
        for (int num : numbers) {
            if (num != 0) isAllZero = false;
            arr.add(String.valueOf(num));
        }
        if (isAllZero) return "0"; // 모든 숫자가 0이면 정답도 0이 된다

        Collections.sort(arr, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.compare(Integer.parseInt(o2 + o1), Integer.parseInt(o1 + o2));
            }
        });
        for (String s : arr) answer += s;
        return answer;
    }
}