Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- dfs
- 수학
- 유니온 파인드
- java
- JUnit 5
- 백트래킹
- 이분탐색
- 투 포인터
- 완전탐색
- Kotlin
- mst
- 시뮬레이션
- 플로이드-와샬
- 알고리즘
- 프로그래머스
- 세그먼트 트리
- swea
- 후니의 쉽게 쓴 시스코 네트워킹
- 문자열
- 구현
- 그리디
- 백준
- CS
- Effective Java
- Network
- BFS
- 에라토스테네스의 체
- 위상정렬
- 동적계획법
- 스택
Archives
반갑습니다!
[프로그래머스] 가장 큰 수 본문
풀이
해당 문제는 숫자를 문자열로 변환한 뒤, 문자열끼리 합친 결과를 비교하는 방법으로 쉽게 해결할 수 있는 문제이다.
코드
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;
}
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[프로그래머스] 징검다리 건너기 (0) | 2020.09.11 |
---|---|
[프로그래머스] 다트 게임 (0) | 2020.09.08 |
[프로그래머스] 더 맵게 (0) | 2020.09.07 |
[프로그래머스] 베스트앨범 (0) | 2020.09.06 |
[프로그래머스] 위장 (0) | 2020.09.06 |