728x90
반응형
https://school.programmers.co.kr/learn/courses/30/lessons/42746
ㆍ문제 설명
0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요.
예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 수는 6210입니다.
0 또는 양의 정수가 담긴 배열 numbers가 매개변수로 주어질 때, 순서를 재배치하여 만들 수 있는 가장 큰 수를 문자열로 바꾸어 return 하도록 solution 함수를 작성해주세요.
ㆍ제한 사항
- numbers의 길이는 1 이상 100,000 이하입니다.
- numbers의 원소는 0 이상 1,000 이하입니다.
- 정답이 너무 클 수 있으니 문자열로 바꾸어 return 합니다.
ㆍ입출력 예
numbers | return |
[6, 10, 2] | "6210" |
[3, 30, 34, 5, 9] | "9534330" |
나의 풀이
- 주어진 숫자의 맨 앞자리 자리수가 큰 수를 문자열에 먼저 붙여야 제일 큰 수를 만들 수 있다.
- 숫자를 덧셈하는 것이 아니라 이어붙이는 것이기 때문에 문자열로 배열에 저장한다.
- 두 문자열을 더하여 정수형으로 변환하였을 때의 숫자를 비교하여 정렬한다.
- 만약, 코드에서 s2가 s1보다 더 크다면 o2가 먼저 오는 것이 더 큰 숫자이기 때문에 양수 반환
-> o2가 o1보다 앞쪽으로 정렬됨
- 만약, 코드에서 s2가 s1보다 더 크다면 o2가 먼저 오는 것이 더 큰 숫자이기 때문에 양수 반환
- 정렬된 배열에서 첫 번째 수가 "0" 이라면 결국 배열의 모든 원소는 "0" 을 의미하기 때문에 "0"을 반환
=> 0은 몇개를 이어붙여도 결국 0이다. - 정렬된 배열의 모든 원소를 이어붙여 만든 값이 가장 큰 수이다.
=> 문자열을 이어붙이는 것은 String.join() 메서드를 사용해도 되고 StringBuilder를 사용해도 됨.
class Solution {
public String solution(int[] numbers) {
String[] number = new String[numbers.length];
for (int i = 0; i < numbers.length; i++) {
number[i] = String.valueOf(numbers[i]);
}
Arrays.sort(number, (
(String o1, String o2) -> {
String s1 = o1 + o2;
String s2 = o2 + o1;
return (int) (Long.parseLong(s2) - Long.parseLong(s1));
}
));
if (number[0].equals("0")) return "0";
StringBuilder builder = new StringBuilder();
for (String num : number) {
builder.append(num);
}
return builder.toString();
}
}
다른 사람의 풀이
- 거의 모든것이 비슷하지만, compareTo() 메서드를 활용하여 큰 수를 비교한 것이 특징
import java.util.Arrays;
public class Solution {
public String solution(int[] numbers) {
String[] arr = new String[numbers.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = String.valueOf(numbers[i]);
}
Arrays.sort(arr, (o1, o2) -> (o2 + o1).compareTo(o1 + o2));
if (arr[0].equals("0")) {
return "0";
}
StringBuilder answer = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
answer.append(arr[i]);
}
return answer.toString();
}
}
728x90
반응형