[Programmers]最大数-JAVA
25477 ワード
📚 Problem
大数
numbers
長さが1以上100000以下numbers
の元素が0以上1000以下📝 Solution
Key Idea
숫자로 0만 주어지는 배열
配列の和を求め、0は「0」4
そのため、元の数字を繰り返して生成した上位4桁を対象に記憶する public String solution(int[] numbers) {
ArrayList<Number> list = new ArrayList<>();
StringBuilder builder = new StringBuilder();
if(Arrays.stream(numbers).sum() == 0)
return "0";
for (int number : numbers)
list.add(new Number(Integer.toString(number)));
for (Number number : list)
number.setChanged();
list.sort((o1, o2) -> {
if (o1.changed.equals(o2.changed))
return Integer.parseInt(o1.original) - Integer.parseInt(o2.original);
return Integer.parseInt(o2.changed) - Integer.parseInt(o1.changed);
});
for(Number number : list)
builder.append(number.original);
return builder.toString();
}
💻 Code
Solution.java
import java.util.ArrayList;
import java.util.Arrays;
class Number {
String original;
String changed;
public Number(String original) {
this.original = original;
}
public void setChanged() {
StringBuilder builder = new StringBuilder();
while (builder.toString().length() <= 4)
builder.append(original);
changed = builder.substring(0, 4);
}
}
class Solution {
public String solution(int[] numbers) {
ArrayList<Number> list = new ArrayList<>();
StringBuilder builder = new StringBuilder();
if(Arrays.stream(numbers).sum() == 0)
return "0";
for (int number : numbers)
list.add(new Number(Integer.toString(number)));
for (Number number : list)
number.setChanged();
list.sort((o1, o2) -> {
if (o1.changed.equals(o2.changed))
return Integer.parseInt(o1.original) - Integer.parseInt(o2.original);
return Integer.parseInt(o2.changed) - Integer.parseInt(o1.changed);
});
for(Number number : list)
builder.append(number.original);
return builder.toString();
}
}
SolutionTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SolutionTest {
Solution solution;
@BeforeEach
public void setSol(){
solution = new Solution();
}
@Test
public void solution_1(){
String result = solution.solution(new int[]{6,10,2});
assertEquals("6210", result);
}
@Test
public void solution_2(){
String result = solution.solution(new int[]{3,30,34,5,9});
assertEquals("9534330", result);
}
@Test
public void solution_3(){
String result = solution.solution(new int[]{1, 10, 100, 1000});
assertEquals("1101001000", result);
}
@Test
public void solution_4(){
String result = solution.solution(new int[]{9,998});
assertEquals("9998", result);
}
@Test
public void solution_5(){
String result = solution.solution(new int[]{30,3021});
assertEquals("303021", result);
}
}
Reference
この問題について([Programmers]最大数-JAVA), 我々は、より多くの情報をここで見つけました https://velog.io/@choi-jaewon/Programmers-가장-큰-수-JAVAテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol