
먼저를 받은 숫자를 배열로 바꿔, 반복문을 통해, 자리수를 비교해서 바꾸는 방법으로 풀었다.
중간에nums[i]로 비교해야햐는데, 그냥 i로 비교해서 오타때문에 시간이 끌렸다.....
첫번째 방법으로 했을 때
class Solution {
public int largestInteger(int number) {
String result = "";
String numStr = String.valueOf(number);
int numLength = numStr.length();
int[] nums = new int[numLength];
for (int i = 0; i < numLength; i++) {
nums[i] = Integer.parseInt(numStr.substring(i, i + 1));
}
for (int i = 0; i < numLength; i++) {
if (nums[i] % 2 != 0) {
for (int j = 0; j < numLength; j++) {
if (i != j) {
if (nums[j] % 2 != 0) {
if (nums[i] > nums[j]) {
int tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
}
}
}
}
} else {
for (int j = 0; j < numLength; j++) {
if (i != j) {
if (nums[j] % 2 == 0) {
if (nums[i] > nums[j]) {
int tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
}
}
}
}
}
}
for (int i = 0; i < numLength; i++) {
result += nums[i];
}
return Integer.parseInt(result);
}
}
두번째 방법 : PriorityQueue
class Solution {
public int largestInteger(int number) {
String result = "";
String numStr = String.valueOf(number);
int numLength = numStr.length();
int [] num = new int [numLength];
int [] boolCheck = new int[numLength];
PriorityQueue<Integer> pq1 = new PriorityQueue(Collections.reverseOrder());
PriorityQueue<Integer> pq2 = new PriorityQueue(Collections.reverseOrder());
for (int i = 0; i < numLength; i++) {
num[i] = Integer.parseInt(numStr.substring(i, i+1));
if(num[i]%2!=0){
boolCheck[i] = 1;
pq1.add(num[i]);
}else{
boolCheck[i] = 2;
pq2.add(num[i]);
}
}
for(int i =0; i<numLength; i++){
if(boolCheck[i]==1){
result+=pq1.poll();
}else{
result+=pq2.poll();
}
}
System.out.println(result);
return Integer.parseInt(result);
}
}
p.s. 정말 고맙다. 문제 이해도.....
처음에 문제 이해를 자리수 홀짝수 인줄 알았더니, 입력값에 자리별 홀짝수를 비교하라는거라니... 처음에는 아래와 같이 풀었다.
class Solution {
public int largestInteger(int number) {
String result = "";
String num = String.valueOf(number);
int numLength = num.length();
int [] nums = new int [numLength];
PriorityQueue pq1 = new PriorityQueue(Collections.reverseOrder());
PriorityQueue pq2 = new PriorityQueue(Collections.reverseOrder());
for(int i = 0; i<numLength; i++){
if(i%2 != 0){
pq1.add(num.charAt(i));
}else{
pq2.add(num.charAt(i));
}
}
for(int i = 0; i<nums.length; i++){
if(i%2 != 0){
result+=pq1.poll();
}else{
result+=pq2.poll();
}
}
return Integer.parseInt(result);
}
}